一、trait类
#ifndef ACCUM_TRAITS_HPP
#define ACCUM_TRAITS_HPP
template<typename T>
struct AccumTraits;
template<>
struct AccumTraits<char>
{
typedef int AccT;
static AccT const zero = 0;
};
template<>
struct AccumTraits<short>
{
typedef int AccT;
static AccT const zero = 0;
};
template<>
struct AccumTraits<int>
{
typedef long AccT;
static AccT const zero = 0;
};
template<>
struct AccumTraits<unsigned int>
{
typedef unsigned long AccT;
static AccT const zero = 0;
};
template<>
struct AccumTraits<float>
{
typedef double AccT;
static AccT const zero = 0;
};
#endif
二、policy类
#ifndef SUM_POLICY_HPP
#define SUM_POLICY_HPP
struct SumPolicy
{
template<typename T1, typename T2>
static void accum(T1& total, T2 const& value)
{
total += value;
}
};
#endif
三、实现类
#ifndef ACCUM_6_HPP
#define ACCUM_6_HPP
#include "trait/accumtraits.hpp"
#include "policy/SumPolicy.hpp"
template< typename T
, typename Policy = SumPolicy
, typename Traits = AccumTraits<T> >
struct Accum6
{
static typename Traits::AccT accum(T const* beg, T const* end)
{
typename Traits::AccT total = Traits::zero;
while (beg != end)
{
Policy::accum(total, *beg);
++beg;
}
return total;
}
};
#endif
四、使用
int num[] = {1, 2, 3, 4, 5, 6};
cout << "avg = " << Accum6<int>::accum(&num[0], &num[sizeof(num)/sizeof(int)]) << endl;