views:

300

answers:

1

Hi,

I am currently working on a small tokenizer template function which also casts the tokens to different objects. this works really nice aslong as all the strucs I cast to have the same number of items. what I would like to do know is to make the function cast to structs with any number of items. The bottleneck of the function for me right now is this: When it was a fixed number(in this case three) of items I did this:

mystruct holder = {items[i], items[i+1], items[i+2]};

Now my idea to be able to cast to structs with different items was to put all items into one array (all the struct items will be of the same type) and simply initialize it like this:

float values[numItems];
for(int j=0; j<numItems; j++) values[j] = items[i+j]
mystruct holder = {values};

But unfortunatelly you cant initialize a struct like this. Does anybody have an idea about how to achieve this? Thanks!

+2  A: 

You can just use a constructor which takes the array as its argument. Structs are basically classes but with a default member visibility of public rather than private.

Troubadour
Thanks, well I thought about that too, but then I would have to have to make them pointers like this:mystruct * holder = new mystruct(values);which i dont want to do.Maybe I could add an init function or something?so I could do:mystruct holder;holder.init(values);Any other ideas?thanks!
moka
ah, i forgot, couldnt I cast an object like this:mystruct holder(values);
moka
Right, it's not a cast, but you'd be passing "values" to the constructor of the struct ("holder" in this case)
Mutmansky
@moka: You don't need a pointer to use constructors. The line in your second comment will do just fine as Mutmansky points out.
Troubadour