Iteration through structural variables

I want to get an iterator for a struct variable in order to set a specific version at runtime according to the enumeration identifier. eg -

struct { char _char; int _int; char* pchar; }; enum { _CHAR, //0 _INT, //1 PCHAR //2 }; int main() { int i = 1; //_INT //if i = 1 then set variable _int of struct to some value. } 

Can you do this without if / else or case case statements?

+4
source share
4 answers

No, C ++ does not support this directly.

However, you can do something very similar using boost :: tuple :

 enum { CHAR, //0 INT, //1 DBL //2 }; tuple<char, int, double> t('b', 1, 3.14); int i = get<INT>(t); // or t.get<INT>() 

You can also take a look at boost :: variant .

+7
source

C ++ does not support this. To sort through the elements of a structure, you need to somehow find out what the members of the structure are. Compiled C ++ programs do not have this information. For them, a structure is just a collection of bytes.

Languages ​​like C # (actually .NET) and Java can do this because they store structure information (reflection information) with the program.

If you really desperately need this function, you can try to implement this by examining the symbol file created by the compiler. It is, however, extremely advanced, and it is unlikely that it is worth the effort.

+3
source

Not. C and C ++ do not allow this.

You need to follow if / else or switch / case statements.

+2
source

Nope. In C ++, you usually do something like this for enumerations:

 enum VarTypes { vtChar = 0, vtInt, vtDouble, vtFirst = vtChar, vtLast = vtDouble }; 

You still need a block of switches to set members in the structure. If you're so addicted, take a look at some of the implementation options in Microsoft code. It is like what you are doing.

+1
source

Source: https://habr.com/ru/post/1300376/