c++通用判零模板类

问题描述:

  1. 对于浮点类型,用 x < epsilon && x > -epsilon 判断,不同的浮点类型有不同的epsilon
  2. 对于整型,用 x==0 判断

思路:

两个模板类,一个Epsilon,一个IsZero,IsZero重载两个构造函数,通过enable_if将浮点类型和整型分开。

//Epsilon class
template<typename type>struct Epsilon{
    typedef typename std::enable_if<std::is_floating_point<type>::value, type>::type T;
};

template<> struct Epsilon<float>{
    constexpr operator float() { return 1e-10f;}
    //static float get(){ return 1e-10f; }
};

template<> struct Epsilon<double>{
    constexpr operator double(){ return 1e-20; }
};

template<> struct Epsilon<long double>{
    constexpr operator long double(){ return 1e-40L;}
};
//IsZero class
template<typename type> struct IsZero{
    //重载两个函数,分类处理
    IsZero(typename std::conditional<std::is_floating_point<type>::value, type, float>::type v){
        f = v < Epsilon<type>() &&
                v > -Epsilon<type>();

        std::cout<<"floating zero check"<<std::endl;
    }

    IsZero(typename std::conditional<std::is_integral<type>::value, type, int>::type v){
        std::cout<<"integer zero check"<<std::endl;
        f = (v == 0);
    }

    operator bool(){
        return f;
    }

private:
    bool f;
};
//Test
int main()
{
    cout<<IsZero<float>(1e-11f)<<endl;
    cout<<IsZero<double>(1e-20)<<endl;
    cout<<IsZero<int>(0)<<endl;

    return 0;
}

结果如下:

//Results
floating zero check
1
floating zero check
0
integer zero check
1

可以看到,对于不同类型的数,会自动调用对应的判别函数。

posted @ 2021-02-03 15:44  wkcagd  阅读(87)  评论(0编辑  收藏  举报