Iterate through struct variables

后端 未结 4 567
孤独总比滥情好
孤独总比滥情好 2020-12-11 08:00

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* pcha         


        
相关标签:
4条回答
  • 2020-12-11 08:34

    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.

    0 讨论(0)
  • 2020-12-11 08:42

    No. C and C++ does not permit this.

    You have to de the if/else or switch/case statements.

    0 讨论(0)
  • 2020-12-11 08:45

    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.

    0 讨论(0)
  • 2020-12-11 08:47

    Nope. In C++ you normally do something like this for enums:

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

    You would still need a switch block to set the members on the struct. If you feel so inclined have a look at some Variant implementation in Microsoft's code. That's kinda similar to what you are doing.

    0 讨论(0)
提交回复
热议问题