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

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

  • 相关阅读:
    PHP网络编程
    traits的使用
    在Apache中使用mod_rewrite模块重写URL
    Lamp下安全配置随笔
    微信开发准备工作
    SQL SERVER技术内幕之7 透视与逆透视
    MVP开发模式的理解
    SQL SERVER技术内幕之5 表表达式
    SQL SERVER技术内幕之4 子查询
    SQL Server Management Studio
  • 原文地址:https://www.cnblogs.com/wkcagd/p/14367424.html
Copyright © 2011-2022 走看看