-
Notifications
You must be signed in to change notification settings - Fork 0
/
c++反射.h
61 lines (51 loc) · 1.69 KB
/
c++反射.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
/*
* File: ReflectClassFactory.h
* Author: stephyang
* 反射类工厂
* Created on 2010年5月12日, 上午9:22
*/
#ifndef _REFLECTCLASSFACTORY_H
#define _REFLECTCLASSFACTORY_H
#include <string>
#include <map>
#include <iostream>
namespace tencent_itil
{
template<class TopBase>
class ReflectClassFactory
{
typedef TopBase* (*TypeCreateFun)();
private:
static std::map<std::string, ReflectClassFactory*>& GetRegTypes()
{
static std::map<std::string, ReflectClassFactory*> types;
return types;
}
const char* _typeName;
TypeCreateFun _typeCreate;
public:
ReflectClassFactory(const char* name, TypeCreateFun create) :
_typeName(name), _typeCreate(create)
{
GetRegTypes()[name] = this;
}
static TopBase *GetInstance(const std::string &typeName)
{
std::map<std::string, ReflectClassFactory*>& types = GetRegTypes();
if (types.find(typeName) == types.end())
{
return NULL;
}
return types[typeName]->_typeCreate();
}
};
//使用该宏定义于类声明中 topbase为基类类名
#define DECLEAR_REFLECT_CLASS(topbase) \
static topbase* GetInstance(); \
static ReflectClassFactory<topbase> *pFactory;
//使用该宏定义与类实现中 topbase为基类类名 classname为该类的类名
#define IMPLEMENT_REFLECT_CLASS(topbase, classname) \
topbase* classname::GetInstance(){return new classname;} \
ReflectClassFactory<topbase> *classname::pFactory = new ReflectClassFactory<topbase>(#classname, classname::GetInstance);
}
#endif /* _REFLECTCLASSFACTORY_H */