2

在用 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。但是,我无法理解浮动数据类型的技巧。有人可以帮忙为花车定义同样的东西。

提前致谢。

4

3 回答 3

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();

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;
};
于 2013-04-18T13:13:55.747 回答
2

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

我建议您改用static const成员变量(或者static constexpr如果您使用的是 C++11 编译器)。

于 2013-04-18T13:14:26.263 回答
1

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

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。标准库模板的这种特化(完全或部分)会导致未定义的行为,除非声明依赖于用户定义的外部链接名称,并且除非特化满足原始模板的标准库要求。» 来自C++ 2003,§17.4.3.1/1

于 2013-04-18T13:13:41.027 回答