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

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...