zoukankan      html  css  js  c++  java
  • c++模板两个数的加法

    1、最简单的情况:

    template<class T>
    T Add(const T& a, const T& b)
    {
    	return a + b;
    }

    缺点是不能够处理不同类型的数据,例如Add(100, 100.0f);

    2、第二种情况:

    template<typename T1, typename T2>
    T1 Add1(T1 lhs, T2 rhs)
    {
    	return lhs + rhs;
    }

    这种情况下,能够处理不同类型的数据,但是有些情况下有些数据精度会丢失,例如:Add(100, 100.1f)

    3、第三种情况:

    这种是根据第二种情况的改良,因为第二种会丢失数据精度主要是因为无法判断两个数据类型的精度,从而确定返回值的类型,利用模板trait技巧,我们可以实现。

    template<bool T,class T1, class T2>
    class IfThenElse;
    
    template<typename T1, typename T2>
    class IfThenElse<true, T1, T2>
    {
    public:
    	typedef T1 ResultT;
    };
    
    template<typename T1, typename T2>
    class IfThenElse<false, T1, T2>
    {
    public:
    	typedef T2 ResultT;
    };
    
    template<typename T1, typename T2>
    class ReturnValueTrait
    {
    public:
    	typedef typename IfThenElse<(sizeof(T1) > sizeof(T2)), T1, T2>::ResultT ResultT;
    };
    
    //因为int和float类型所占的字节相同,所以无法通过比较大小来判断类型的精度,需要偏特化
    template<>
    class ReturnValueTrait<float, int>
    {
    public:
    	typedef float ResultT;
    };
    
    template<>
    class ReturnValueTrait<int, float>
    {
    public:
    	typedef float ResultT;
    };
    
    template<typename t1, typename t2>
    typename ReturnValueTrait<t1, t2>::ResultT Add(T1 lhs, T2 rhs)
    {
    	return lhs + rhs;
    }
    


     

  • 相关阅读:
    c++中sort等算法中比较操作的规则
    数据结构(c++)(1)-- 栈
    Problem 10: Summation of primes
    Problem 9: Special Pythagorean triplet
    Problem 7: 10001st prime
    Problem 8: Largest product in a series
    Problem 5: Smallest multiple
    Problem 6: Sum square difference
    Problem 4: Largest palindrome product
    Problem 3: Largest prime factor
  • 原文地址:https://www.cnblogs.com/dongc/p/5225129.html
Copyright © 2011-2022 走看看