Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enumerate members of a structure?

Tags:

c++

c

enumeration

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);
like image 797
Mike Avatar asked May 20 '09 15:05

Mike


People also ask

Who are the members of structure?

A structure contains an ordered group of data objects. Unlike the elements of an array, the data objects within a structure can have varied data types. Each data object in a structure is a member or field. A union is an object similar to a structure except that all of its members start at the same location in memory.

What is members of structure in C++?

Structures (also called structs) are a way to group several related variables into one place. Each variable in the structure is known as a member of the structure. Unlike an array, a structure can contain many different data types (int, string, bool, etc.).

What is member function structure?

Declaring a function as a member of a struct has precisely the same semantics as declaring a function as a member of a class, except for the difference you've noted. In each case they are called member functions.


1 Answers

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.

like image 60
paxos1977 Avatar answered Oct 08 '22 15:10

paxos1977