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

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

  • 相关阅读:
    《Apache Velocity用户指南》官方文档
    Mockito教程
    GitHub访问速度慢的解决方法
    使用log4jdbc记录SQL信息
    分环境部署SpringBoot日志logback-spring.xml
    SpringBoot入门之spring-boot-maven-plugin
    swagger报No operations defined in spec!
    delphi 时间
    DELPHI常用类型及定义单元
    delphi 多线程编程
  • 原文地址:https://www.cnblogs.com/wkcagd/p/14367424.html
Copyright © 2011-2022 走看看