定义浮点数的值特征

Defining value traits for floating points

本文关键字:特征 浮点数 定义      更新时间:2023-10-16

在用c++编写一些代码时,我想表达这样一个概念:对于类型X的组件,它的最小值是kMinValue,它的最大值是kMaxValue。为此,我做了如下操作:

template <typename ComponentType>
struct CompTraits
{
};
template <>
struct CompTraits<unsigned char>
{
    typedef unsigned char ComponentType;
    enum{
        kMinValue = 0,
        kMaxValue = 255
    };              
};

,我可以参考CompTraits<unsigned char>::kMinValue。但是,我无法理解浮动数据类型的技巧。有人可以帮助定义相同的东西为浮动。

您可以使用std::numeric_limits,而不是您的常量,但如果您只想要kMinValuekMaxValue -您可以使用以下内容

c++ 03

template<>
struct CompTraits<float>
{
   static const float kMinValue;
   static const float kMaxValue;
};
const float CompTraits<float>::kMinValue = std::numeric_limits<float>::min();
const float CompTraits<float>::kMaxValue = std::numeric_limits<float>::max();
c++ 11

template<>
struct CompTraits<float>
{
   static constexpr float kMinValue = std::numeric_limits<float>::min();
   static constexpr float kMaxValue = std::numeric_limits<float>::max();
};

对于您的情况,您只需使用

template<>
struct CompTraits<float>
{
   static const float kMinValue = 0.0f;
   static const float kMaxValue = 1.0f;
};

这是因为您使用enum作为常量。枚举常量只能是整数。

我建议你使用static const成员变量代替(或static constexpr,如果你使用c++ 11编译器)。

您不能使用enum 来定义这些值,因为enum只能存储整数值,您可以使用常量代替:

template <>
struct CompTraits<double>
{
    typedef double ComponentType;
    static const double kMinValue = 0.;
    static const double kMinValue = 1.;          
};

对于标准数值类型,您可以查看c++ STL的std::numeric_limit。

numeric_limits<unsigned char>::min() 将做与您的CompTraits<unsigned char>::kMinValue相同的事情,并且它适用于所有数字类型。

还需要注意的是,您可以将numeric_limit专门化为您自己的数据类型:

namespace std {
    template<>
    struct numeric_limits<YourType>
    {
        static const bool is_specialized = true;
        /* assuming YourType has a constructor from double */
        static const YourType min() throw() { return 0. };
        static const YourType max() throw() { return 1. };
    };
}

如果您对这种方法的合法性有疑问,请参见:

«程序可以添加模板特化将任何标准库模板命名为std标准库模板的专门化(全部或部分)导致未定义的行为,除非声明依赖于外部链接的用户自定义名称,除非专门化满足标准库对原始模板的要求from c++ 2003,§17.4.3.1/1