zoukankan      html  css  js  c++  java
  • 模板的Traits

    Traits含义就是特性,应用Trait模板参数,使得我们的程序既保持灵活性,同时减少类型参数的数量。能够使得我们对函数进行更加细粒度的控制。


    #ifndef TRAIT_H_
    #define TRAIT_H_
    /*
    template<typename T>
    T accumulate( const T *begin, const T *end )
    {
        T total = T();
    
        while ( begin != end ) {
            total += *begin;
            ++begin;
        }
    
        return total;
    }*/
    
    
    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 long AccT;
        static AccT zero() {
            return 0;
        }
    };
    
    template<>
    class AccumulationTraits<unsigned int>
    {
    public:
        typedef unsigned long long AccT;
        static AccT zero() {
            return 0;
        }
    };
    
    template<>
    class AccumulationTraits<float>
    {
    public:
        typedef double AccT;
        static AccT zero() {
            return 0;
        }
    };
    
    template<typename T, typename AT = AccumulationTraits<T> >
    class Accum
    {
    public:
        static typename AT::AccT accumulate( const T *begin, const T *end ) {
            typename AT::AccT total = AT::zero();
    
            while ( begin != end ) {
                total += *begin;
                ++begin;
            }
    
            return total;
        }
    };
    
    template<typename T>
    typename AccumulationTraits<T>::AccT accumulate( const T *begin,
            const T *end )
    {
        return Accum<T>::accumulate( begin, end );
    }
    
    template<typename Traits, typename T>
    typename Traits::AccT accumulate( const T *begin, const T *end )
    {
        return Accum<T, Traits>::accumulate( begin, end );
    }
    
    #endif
    int iv[5] = {1, 2, 3, 4, 5};
    double ftotal = accumulate<typename AccumulationTraits<float>, int>( iv, iv + sizeof( iv ) / sizeof( int ) );
    EXPECT_EQ( 15,  ftotal );
    
    char cv[] = {'a', 'a', 'b', 'b'};
    int total = 97 * 2 + 98 * 2;
    EXPECT_EQ( total , accumulate( cv, cv + sizeof( cv ) / sizeof( char ) ) );
  • 相关阅读:
    3524: [Poi2014]Couriers -- 主席树
    bzoj 2190: [SDOI2008]仪仗队 -- 欧拉函数
    模板 -- 树链剖分
    bzoj 1823: [JSOI2010]满汉全席 -- 2-sat
    bzoj 1704: [Usaco2007 Mar]Face The Right Way 自动转身机 -- 贪心
    bzoj 1231: [Usaco2008 Nov]mixup2 混乱的奶牛 -- 状压DP
    redis 主从复制
    redis 事务
    redis持久化——AOF
    redis 持久化 ——RDB
  • 原文地址:https://www.cnblogs.com/riskyer/p/3310773.html
Copyright © 2011-2022 走看看