- 论坛徽章:
- 0
|
c++模板应用之--traits
利用c++的模板技术可以极大抽象程序的设计和实现,扩展性会变的很强 。c++的很多有名的库都利用了c++的模板技术,并且复合了许多设计模式 。c++ 实现的trait可以解决很多实际问题比如我要实现一个账目汇总的模块那么可能我要实现这样一个求和函数long sum( int a, int b) ;但是我们某时刻我不需要如此传入int参数而是传入一个float那么我们肯能会定义另一个函数double sum( float a, float b) ;有人说多加一个sum的 重载很ok啊, 但是在现实应用中并不会总是这么让你随意,尤其平台开发中更应该将接口设计的很抽象我定义一个trait template
class traits ;
template
class traits
{
public:
typedef long Acct ;
enum{ zero = 0 };
};
template
class traits
{
public:
typedef double Acct ;
static Acct const zero ;
};
double const traits::zero = 0.0 ;那么我定义sum函数可以这样templateclass traits::Acct sum( T * a ,std::size_t size ){ typedef class traits::Acct Acct ; Acct total = traits::zero ; for( std::size_t i =0 ; i { total += *(a +i) ; } return total ;}
这样我们就可以这样自如的运用sum 了
int main(){ int arrI [ 6] ={ 21 ,90 ,21 ,90 ,21 ,90} ; float arrF [ 6 ] ={ 21.5 ,90.8,21.5 ,90.8 ,21.5 ,90.8} ; cout
cout return 0;}
好了,我的trait运行正常了
本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u3/109133/showart_2142537.html |
|