c++模拟反射机制-方法1

来源:互联网 发布:linux 查看防火墙端口 编辑:程序博客网 时间:2024/06/06 01:58
用map实现反射的简单例子。

C/C++ code
?
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
#include <iostream>
#include <string>
#include<map>
 
using namespace std;
 
 
class Base
{public:
    virtual void say()=0;
};
 
class A:public Base
{public:
    virtual void say()
    {
        cout<<"This is A"<<endl;
    }
};
 
class B:public Base
 
{public:
    virtual void say()
    {
        cout<<"This is B"<<endl;
    }
};
 
template <typename T>
Base *Create()                  //创建函数
{
    return new T;
}
 
typedef Base*(*FUN)();
map<string, FUN> rmap;      //由类名到创建函数的映射
 
 
 
int main() 
{
    rmap["A"]=Create<A>;     //注册
    rmap["B"]=Create<B>;     //注册
 
    string str="A";
 
    Base* p=rmap[str]();     //动态创建
    p->say();
    delete p;
 
    str="B";
    p=rmap[str]();         //动态创建
    p->say();
    delete p;
 
 
}