traits

#include<iostream>
using namespace std;


template<typename T>
class AccumulationTraits{
public:
    typedef T AccT;
    static const AccT zero=0;
};

template<>
class AccumulationTraits<char>{
public:
    typedef int AccT;//防止char计算时越界
    static const AccT zero=0;
};

template<typename T>
inline typename AccumulationTraits<T>::AccT accum(const T* beg,const T* end)
{
    typedef typename AccumulationTraits<T>::AccT AccT;
    //AccT total = T();
    AccT total = AccumulationTraits<T>::zero;//防止没有T()==0
    while(beg!=end){
        total+=*beg;
        ++beg;
    }
    return total;
}

int main()
{
    int c = int();
    cout << "test int()=" << c << endl;
    int num[] = {1,2,3,4,5};
    cout << accum(&num[0],&num[5])/5 << endl;

    char name[]="templates";
    //char的范围是-128~127
    cout << accum(&name[0],&name[5])/5<<endl;
}

test int()=0
3
109

你可能感兴趣的:(C++,c,C#)