Aamir
Aamir

Reputation: 15576

Getting name and type of a struct field from its object

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.

Upvotes: 6

Views: 35671

Answers (4)

Thomas Matthews
Thomas Matthews

Reputation: 57739

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.

Upvotes: 0

Björn Pollex
Björn Pollex

Reputation: 76856

You are asking for Reflection in C++.

Upvotes: 14

Goz
Goz

Reputation: 62333

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 ...

Upvotes: 1

Sebastian
Sebastian

Reputation: 4950

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;

Upvotes: 3

Related Questions