C++ trait example

来源:互联网 发布:php开发api接口教程 编辑:程序博客网 时间:2024/06/06 03:51

 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;
}


原创粉丝点击