an example modified
#include<iostream>
using namespace std;
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 AccT;
static AccT zero(){
return 0;
}
};
template<typename T,typename AT = AccumulationTraits<T> >
class Accum{
public:
static typename AT::AccT accum(T const * beg,T const * end){
typename AT::AccT total = AT::zero();
while(beg !=end){
total += *beg;
++beg;
cout<<" abcd"<<endl;
}
return total;
}
};
int main()
{
const int num[5] = {1,2,3,4,5};
//accum(&num[0],&num[4]);
typedef Accum <char> test;
test testabc;
const char testchar[8] = "abcdefg";
// testabc(&testchar[0],&testchar[7]);
char testa = 'a';
char testb = 'b';
const char * ptesta = &testa;
const char * ptestb = &testb;
//testabcthis->init(__sb)
testabc.accum(&testchar[0],&testchar[7]);
Accum<char> test2;
//test2 test3; //
//test3.Accum(&testchar[0],&testchar[7]); //error,should be an typedef then object value
return 0;
}
本文介绍了一个使用C++模板元编程实现的累加器类,该类能够根据不同类型的输入选择合适的累加方式,并演示了如何为char、short和int类型定义特定的行为。通过实例展示了如何使用这个累加器类来处理字符数组。
7287

被折叠的 条评论
为什么被折叠?



