标签:
#ifndef ACCUM_HPP#define ACCUM_HPPtemplate <typename T>inlineT accum (T const* beg, T const* end){T total = T(); // assume T() actually creates a zero valuewhile (beg != end) {total += *beg;++beg;}return total;}#endif // ACCUM_HPP
#include "accum1.hpp"#include <iostream>int main(){// create array of 5 integer valuesint num[]={1,2,3,4,5};// print average valuestd::cout << "the average value of the integer values is "<< accum(&num[0], &num[5]) / 5<< ‘\n‘;// create array of character valueschar name[] = "templates";int length = sizeof(name)-1;// (try to) print average character valuestd::cout << "the average value of the characters in \""<< name << "\" is "<< accum(&name[0], &name[length]) / length<< ‘\n‘;}
存在问题,当调用的是char时,模板自动将返回函数也定义为char,而不是期望的int。
模板定义
template<typename T>class AccumulationTraits;template<>class AccumulationTraits<char> {public:typedef int AccT;};template<>class AccumulationTraits<short> {public:typedef int AccT;};template<>class AccumulationTraits<int> {public:typedef long AccT;};template<>class AccumulationTraits<unsigned int> {public:typedef unsigned long AccT;};template<>class AccumulationTraits<float> {public:typedef double AccT;};template <typename T>inlinetypename AccumulationTraits<T>::AccT accum (T const* beg,T const* end){// return type is traits of the element typetypedef typename AccumulationTraits<T>::AccT AccT;AccT total = AccT(); // assume T() actually creates a zero valuewhile (beg != end) {total += *beg;++beg;}return total;}
zero()
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<>class AccumulationTraits<unsigned int> {public:typedef unsigned long AccT;static AccT zero() {return 0;}};template<>class AccumulationTraits<float> {public:typedef double AccT;static AccT zero() {return 0;}};template <typename T>inlinetypename AccumulationTraits<T>::AccT accum (T const* beg,T const* end){// return type is traits of the element typetypedef typename AccumulationTraits<T>::AccT AccT;AccT total = AccumulationTraits<T>::zero();while (beg != end) {total += *beg;++beg;}return total;}
function traits的方法
template <typename T>inlinetypename AccumulationTraits<T>::AccT accum (T const* beg,T const* end){return Accum<T>::accum(beg, end);}template <typename Traits, typename T>inlinetypename Traits::AccT accum (T const* beg, T const* end){return Accum<T, Traits>::accum(beg, end);}
function traits方法引入Class
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;}return total;}};
标签:
原文地址:http://www.cnblogs.com/kongww/p/5425373.html