首页 > 其他 > 详细

定义trais类

时间:2016-04-10 14:14:25      阅读:221      评论:0      收藏:0      [点我收藏+]
 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 }

 

定义trais类

原文:http://www.cnblogs.com/ppplus/p/5373877.html

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