Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate through struct variables

Tags:

c++

iterator

I want to get an iterator to struct variable to set a particular one on runtime according to enum ID. for example -

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 that without if/else or switch case statements?

like image 456
cpx Avatar asked Dec 14 '22 00:12

cpx


2 Answers

No, C++ doesn't support this directly.

You can however 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 might also want to take a look at boost::variant.

like image 185
Alex Jenter Avatar answered Dec 15 '22 12:12

Alex Jenter


C++ doesn't support this. To iterate over struct members, you'll need some way to know what the struct members are. Compiled C++ programs don't posess this information. To them, a struct is just a collection of bytes.

Languages like C# (anything .NET actually) and Java can do this because they store information about the structs (reflection information) along with the program.

If you're really desperate for this feature, you could try to implement this by parsing the symbols file created by the compiler. This, however, is extremely advanced and it is unlikely that it is worth the effort.

like image 32
Ondergetekende Avatar answered Dec 15 '22 12:12

Ondergetekende