Storing Datatype Information

1.5k views Asked by At

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'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?

4

There are 4 answers

1
Steve On BEST ANSWER

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.

0
Nim On

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).

1
BЈовић On

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

0
BR41N-FCK On

A tuple would also do the job.

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