模板的Traits
来源:互联网 发布:ubuntu vnc客户端 编辑:程序博客网 时间:2024/06/04 18:52
Traits含义就是特性,应用Trait模板参数,使得我们的程序既保持灵活性,同时减少类型参数的数量。能够使得我们对函数进行更加细粒度的控制。
#ifndef TRAIT_H_#define TRAIT_H_/*template<typename T>T accumulate( const T *begin, const T *end ){ T total = T(); while ( begin != end ) { total += *begin; ++begin; } return total;}*/template<typename T>class AccumulationTraits;template<>class AccumulationTraits<char>{public: typedef int AccT; static AccT zero() { return 0; }};template<>class AccumulationTraits<short>{public: typedef int AccT; static AccT zero() { return 0; }};template<>class AccumulationTraits<int>{public: typedef long long AccT; static AccT zero() { return 0; }};template<>class AccumulationTraits<unsigned int>{public: typedef unsigned long long AccT; static AccT zero() { return 0; }};template<>class AccumulationTraits<float>{public: typedef double AccT; static AccT zero() { return 0; }};template<typename T, typename AT = AccumulationTraits<T> >class Accum{public: static typename AT::AccT accumulate( const T *begin, const T *end ) { typename AT::AccT total = AT::zero(); while ( begin != end ) { total += *begin; ++begin; } return total; }};template<typename T>typename AccumulationTraits<T>::AccT accumulate( const T *begin, const T *end ){ return Accum<T>::accumulate( begin, end );}template<typename Traits, typename T>typename Traits::AccT accumulate( const T *begin, const T *end ){ return Accum<T, Traits>::accumulate( begin, end );}#endif
int iv[5] = {1, 2, 3, 4, 5};double ftotal = accumulate<typename AccumulationTraits<float>, int>( iv, iv + sizeof( iv ) / sizeof( int ) );EXPECT_EQ( 15, ftotal );char cv[] = {'a', 'a', 'b', 'b'};int total = 97 * 2 + 98 * 2;EXPECT_EQ( total , accumulate( cv, cv + sizeof( cv ) / sizeof( char ) ) );
- 模板的Traits
- C++的Char traits模板类
- C++的Char traits模板类
- C++模板 - traits
- C++模板 - value traits
- C++模板 - traits & policy
- C++模板-Traits
- c++模板元编程七:类型判断的traits类
- [function & type_traits] VC6 的 function traits 和 function 模板的新的实现方法
- 【C++模版之旅】项目中一次活用C++模板(traits)的经历
- 【C++模版之旅】项目中一次活用C++模板(traits)的经历。-新注解
- 模板的使用:Promotion Traits( 类型提升之特征萃取)
- traits的应用场合
- traits技术的应用
- PHP Traits 的学习
- Traits的用法
- Traits的用法
- C++的Traits
- [Oracle 11.2.0.3] Modify Hostname on GI (standalone server)
- Uninstall Skype with WindowsUninstaller.Org Removal Tips
- PASCAL VOC
- 设计模式之Observer
- urlrewrite重写
- 模板的Traits
- Myeclipse7.5安装FindBugs检查代码Bug
- Unity3D协同程序(Coroutine)
- ios 动画
- UITableView的讲解
- android 中文转成拼音
- android开源项目和框架
- C/C++定义全局变量/常量几种方法的区别
- hdu 4712 Hamming Distance