反射(一)

C++不像C#,java那样天生编译过程实现反射功能,只能在代码层面注册来实现。比如QT,UE等,为了实现反射功能,提供了特殊的宏定义,并且使用工具将宏生成相应的C++代码实现反射功能的。

1.定义

 1 class ClassProperty;
 2 class Object
 3 {
 4 public:
 5     int getIntValue(int i) { return i + 1; }
 6 public:
 7     virtual const ClassProperty* getProperty()
 8     {
 9         return GetClassPropertys();
10     }
11 public:
12     static  const ClassProperty* GetClassPropertys();
13 };
14 struct ClassProperty
15 {
16 private:
17     typedef void* (Object::*Func)(void*);
18 public:
19     ClassProperty() :func(nullptr), desc(nullptr) {}
20     template<typename R, typename C, typename... Args>
21     ClassProperty(R(C::*funcc)(Args...)const = 0, const char* desc = 0) :
22         desc(desc)
23     {
24         typedef R(Object::*ObjFunc)(Args...);
25         func = (Func)(ObjFunc)funcc;
26     }
27     template<typename R, typename C, typename... Args>
28     ClassProperty(R(C::*funcc)(Args...) = 0, const char* desc = 0) :
29         desc(desc)
30     {
31         typedef R(Object::*ObjFunc)(Args...);
32         func = (Func)(ObjFunc)funcc;
33     }
34 public:
35     template<typename R, typename ...Args>R invoke(Object* obj, Args&&... args)const
36     {
37         typedef R(Object::*ObjFunc)(Args...);
38         ObjFunc mf = (ObjFunc)func;
39         return (obj->*mf)(std::forward<Args>(args)...);
40     }
41     Func  func;
42     const char* desc;
43 };
44 const ClassProperty* Object::GetClassPropertys()
45 {
46     const static ClassProperty prop[] = { { &Object::getIntValue,"getIntValue" },ClassProperty() };
47     return prop;
48 }

2.使用

1     Object* obj = new Object();
2     const ClassProperty* prop = obj->getProperty();
3     while (prop->func != nullptr) {
4         std::cout << prop->desc << std::endl;
5         int ret = prop->invoke<int, int>(obj, 2);
6         std::cout << ret << std::endl;
7         prop++;
8     }
9     delete obj;

3.结果

   getIntValue

   2

   这里实现的反射功能还是很简单,没有对输入参数,输出参数类型进行判断,反射仅实现了简单函数的功能,没有成员变量,静态函数,以及复杂参数等功能。

转载于:https://www.cnblogs.com/goooon/p/5650660.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值