首页 > 其他 > 详细

属性&&反射

时间:2016-07-07 19:50:40      阅读:190      评论:0      收藏:0      [点我收藏+]

C++不像C#,java那样天生带有反射功能,只能在代码层面来实现。

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

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

属性&&反射

原文:http://www.cnblogs.com/goooon/p/5650660.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!