Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
471 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...