定义浮点的值特征

Aar*_*kan 2 c++ template-specialization

在用c ++编写一些代码时,我想表达一个概念,即对于X类型的组件,它的最小值是kMinValue,它的最大值是kMaxValue.为此,我做了类似的事情:

template <typename ComponentType>
struct CompTraits
{

};

template <>
struct CompTraits<unsigned char>
{
    typedef unsigned char ComponentType;
    enum{
        kMinValue = 0,
        kMaxValue = 255
    };              
};
Run Code Online (Sandbox Code Playgroud)

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

提前致谢.

For*_*veR 5

您可以使用std::numeric_limits,而不是您的常量,但如果您只想- kMinValue并且kMaxValue- 您可以使用这样的东西

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();
Run Code Online (Sandbox Code Playgroud)

C++ 11

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

对于你的情况,你应该使用

template<>
struct CompTraits<float>
{
   static const float kMinValue = 0.0f;
   static const float kMaxValue = 1.0f;
};
Run Code Online (Sandbox Code Playgroud)