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
2.3k views
in Technique[技术] by (71.8m points)

c++ - Enumerate members of a structure?

Is there a way to enumerate the members of a structure (struct | class) in C++ or C? I need to get the member name, type, and value. I've used the following sample code before on a small project where the variables were globally scoped. The problem I have now is that a set of values need to be copied from the GUI to an object, file, and VM environment. I could create another "poor man’s" reflection system or hopefully something better that I haven't thought of yet. Does anyone have any thoughts?

EDIT: I know C++ doesn't have reflection.

union variant_t {
   unsigned int  ui;
   int           i;
   double        d;
   char*         s;
};

struct pub_values_t {
   const char*      name;
   union variant_t* addr;
   char             type;  // 'I' is int; 'U' is unsigned int; 'D' is double; 'S' is string
};

#define pub_v(n,t) #n,(union variant_t*)&n,t
struct pub_values_t pub_values[] = {
   pub_v(somemember,  'D'),
   pub_v(somemember2, 'D'),
   pub_v(somemember3, 'U'),
   ...
};

const int no_of_pub_vs = sizeof(pub_values) / sizeof(struct pub_values_t);
See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

To state the obvious, there is no reflection in C or C++. Hence no reliable way of enumerating member variables (by default).

If you have control over your data structure, you could try a std::vector<boost::any> or a std::map<std::string, boost::any> then add all your member variables to the vector/map.

Of course, this means all your variables will likely be on the heap so there will be a performance hit with this approach. With the std::map approach, it means that you would have a kind of "poor man's" reflection.


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

...