tags:

views:

138

answers:

4

For example, I have a struct which is something like this:

struct Test
{
    int i;
    float f;
    char ch[10];
};

And I have an object of this struct such as:

Test obj;

Now, I want to programmatically get the field names and type of obj. Is it possible?

This is C++ BTW.

+3  A: 

I'm afraid you cannot get the field names, but you can get the type of obj using Boost.Typeof:

#include <boost/typeof/typeof.hpp>
typedef BOOST_TYPEOF(obj) ObjType;
Sebastian
+1  A: 

No its not possible without writing your own "struct" system. You can get the sizeof of a member but you need to know its name. C++ does not allow you, to my knowledge, to enumerate at compile or run-time the members of a given object. You could put a couple of functions such as "GetNumMembers()" and "GetMemberSize( index )" etc to get the info you are after ...

Goz
+7  A: 

You are asking for Reflection in C++.

Space_C0wb0y
A: 

You may also want to search the web for "C++ serialization", especially the Boost libraries. I'd also search Stack Overflow for "C++ serialization".

Many C++ newbies would like to create object instances from a class name or fill in class fields based on names. This is where Serialization or Deserialization comes in handy.

My experience needing class and member names comes from printing debug information. Class and field names would be useful when handling exceptions, especially generating them.

Thomas Matthews