开发者

Storing Datatype Information

Let's say I have a few variables of different types.

int MyInteger;
double MyDouble;
char MyChar;

Pointers to these variables are stored in a single array of void pointers.

void* IntegerPointer = &MyInteger;
void* DoublePointer = &MyDouble;
void* CharPointer = &MyChar;

void* PointerArray[] = {IntegerPointer, DoublePointer, CharPointer};

I'开发者_Go百科d like to store the datatype information in a parallel array. type_info seems to be suited to the task, but assignment isn't supported. So I can't just do something like this:

type_info TypeInfoArray[] = {int, double, char};

Is there any other way to store information about a datatype?


I suggest you use a variant type. I hate to say it, but try boost::variant (or something similar). Forget all this parallel array and void pointer stuff; a single array of variants achieves the same thing and is more elegant.


Take a look at typeinfo. Then you can store type info as an array of std::string


If you are looking for a container to hold a sequence of different types, look no further than boost::fusion.

For example, if you use a fusion sequence for your types,

fusion::vector<int, double, char> object_array(1, 2.0, 'F');

Now, to get what's at index 0 for example

at<0>(object_array); // will provide a reference to the int field

It's perfectly type safe, and not a void * in sight... The only downside is that there is a limit to the number of "elements" you can have in the sequence (typically the number of template parameters as enforced by the compiler).


A tuple would also do the job.

std::tuple<int*,float*> tp (&yourInt, &yourFloat);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜