Distinguishing integer from floating point types in a template

前端 未结 3 1114
逝去的感伤
逝去的感伤 2021-02-09 13:27

I\'d like to perform similar, but not identical computations for several integer types (16, 32, 64 bits) and floating point types (float, double, long double). Most of the code

3条回答
  •  礼貌的吻别
    2021-02-09 13:55

    With C++11 it is possible to use type traits. See std::enable_if documentation In your case, it might look like this:

    Function parameter specialization:

    template
    bool isEqual(T a, T b, typename std::enable_if::value >::type* = 0) 
    {
        return a == b;
    }
    
    template
    bool isEqual(T a, T b, typename std::enable_if::value >::type* = 0) 
    {
        return abs( a - b ) < epsilon;
    }
    

    Return type specialization:

    template
    typename std::enable_if::value, bool >::type isEqual(T a, T b)
    
    {
        return a == b;
    }
    
    template
    typename std::enable_if::value, bool >::type isEqual(T a, T b)
    {
        return abs( a - b ) < epsilon;
    }
    

提交回复
热议问题