定义trais类

 1 // 先定义两种类型
 2 struct A{};
 3 struct B{};
 4 
 5 class Foo
 6 {
 7 public:
 8     // 将类型A绑定到Foo
 9     typedef A classtype;
10 
11     void foo()
12     {
13         std::cout << __FUNCTION__ << std::endl;
14     }
15 };
16 
17 class Bar
18 {
19 public:
20     // 将类型B绑定到Bar
21     typedef B classtype;
22 
23     void bar()
24     {
25         std::cout << __FUNCTION__ << std::endl;
26     }
27 };
28 
29 // 可选,为Foo Bar定义一个traits类
30 template<typename T>
31 class test_traits
32 {
33 public:
34     typedef typename T::classtype classtype;
35 };
36 
37 // 定义一个以Foo Bar为参数的模板函数
38 template<typename T>
39 void func()
40 {
41     // 如果不定义traits类,这里可以直接使用T::classtype
42     do_func(T(), test_traits<T>::classtype());
43 }
44 
45 // func函数真的A类型class的实现
46 template<typename T>
47 void do_func(T &ins, A a)
48 {
49     ins.foo();
50 }
51 
52 // func函数真的B类型class的实现
53 template<typename T>
54 void do_func(T &ins, B a)
55 {
56     ins.bar();
57 }
58 
59 int main(void)
60 {
61     func<Foo>();
62     func<Bar>();
63 }

 

posted @ 2016-04-10 13:13  我们的时光  阅读(251)  评论(0编辑  收藏  举报