引出问题:
给定一个我们自己定义的类A,如何便捷的输出其所有的成员变量类型及值。
日常编程中有这样的需求,一个是为了调试,二个是为了在不同模块运行时得到类的属性用于显示及修改。但C++未提供原生的反射机制,所以有了以下思考。
核心的需求为:对于一个类型A,我们可以拥有其所有的类型信息。例如:
class A
{
int INT;
float FLT;
}
/*MAIN*/
A a;
a.INT = 1;
a.FLT = 2.0f;
{
for(auto& var : a.attr())
cout << var;
}
其输出结果应类似:
int INT 1
float FLT 2.0
找了一些资料来看,我们手头上已经有了一个实现版本,直接给出源码:
#include <iostream>
#include <vector>
#include <map>
#include <string>
#define _OFFSET_(_Obj_Ty,_Key) \
((unsigned long)(&((_Obj_Ty *)0)->_Key))
#define CLASS_REGISTER(_Obj_Ty) \
public: \
static tat::tat_class * get_class_ptr() \
{ \
static tat::tat_class __class_##_Obj_Key##__; \
return &__class_##_Obj_Key##__; \
}
#define FIELD_REGISTER(_Access,_Field_Ty,_Field_Key,_Obj_Ty) \
_Access: \
_Field_Ty _Field_Key; \
private: \
class __field_register_##_Field_Key##__ \
{ \
public: \
__field_register_##_Field_Key##__() \
{ \
static tat::__field_register__ reg_##_Field_Key( \
_Obj_Ty::get_class_ptr(), \
_OFFSET_(_Obj_Ty,_Field_Key), \
#_Field_Key); \
} \
}_Field_Key