上篇博客讲到类型信息必须通过函数模板来传递,
但是有个特殊的函数可以再把这个信息传递给类!~~~那就是构造函数
这正是ANY的实现:
1 class any
2 {
3 public: // structors
4
5 any()
6 : content(0)
7 {
8 }
9
10 template<typename ValueType>
11 any(const ValueType & value)
12 : content(new holder<ValueType>(value))
13 {
14 }
15
16 any(const any & other)
17 : content(other.content ? other.content->clone() : 0)
18 {
19 }
20
21 ~any()
22 {
23 delete content;
24 }
25 //……
26 #ifndef BOOST_NO_MEMBER_TEMPLATE_FRIENDS
27
28 private: // representation
29
30 template<typename ValueType>
31 friend ValueType * any_cast(any *);
32
33 template<typename ValueType>
34 friend ValueType * unsafe_any_cast(any *);
35
36 #else
37
38 public: // representation (public so any_cast can be non-friend)
39
40 #endif
41
42 placeholder * content;
43
44 };
这是它的构造函数、拷贝构造函数和析构函数,content是一个placeholder的指针。从使用的角度看,any在实例化时,可以用任何类型的数据来初始化,除了用any以外,其它的数据类型时,都会调用那个模板构造函数,它将生成一个holder对象,把初始数据存放在该对象中,同时把该holder对象的指针存放在成员变量content中。由此可知,holder类肯定是从placeholder类继承而来的,之后的代码中就可以见证到这一点。Boost根据编译器是否支持成员模板友员,特地小心地处理了any_cast和unsafe_any_cast两个辅助函数。
1 class placeholder
2 {
3 public: // structors
4
5 virtual ~placeholder()
6 {
7 }
8
9 public: // queries
10
11 virtual const std::type_info & type() const = 0;
12
13 virtual placeholder * clone() const = 0;
14
15 };
16
17 template<typename ValueType>
18 class holder : public placeholder
19 {
20 public: // structors
21
22 holder(const ValueType & value)
23 : held(value)
24 {
25 }
26
27 public: // queries
28
29 virtual const std::type_info & type() const
30 {
31 return typeid(ValueType);
32 }
33
34 virtual placeholder * clone() const
35 {
36 return new holder(held);
37 }
38
39 public: // representation
40
41 ValueType held;
42
43 };