zoukankan      html  css  js  c++  java
  • 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

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

  • 相关阅读:
    淘宝质量属性场景分析
    关于软件架构师如何工作(阅读架构漫谈感悟)
    06有效需求设计阅读笔记之六
    05有效需求设计阅读笔记之五
    xxx征集系统项目目标文档
    04有效需求设计阅读笔记之四
    03有效需求设计阅读笔记之三
    02有效需求设计阅读笔记之二
    01有效需求设计阅读笔记之一
    问题账户需求分析
  • 原文地址:https://www.cnblogs.com/wkcagd/p/14367424.html
Copyright © 2011-2022 走看看