Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
477 views
in Technique[技术] by (71.8m points)

c++ - Iterate through struct variables

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...