开发者

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 ty开发者_如何学编程pe of obj. Is it possible?

This is C++ BTW.


You are asking for Reflection in C++.


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;


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜