定义浮点数的值特征
Defining value traits for floating points
在用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
,而不是您的常量,但如果您只想要kMinValue
和kMaxValue
-您可以使用以下内容
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
相关文章:
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 如何修复此错误:未定义对"距离(浮点数,浮点数,浮点数,浮点数,浮点数)"的引用
- C++浮点数据类型和字符串数据类型无法子到模板函数中
- 使用提升将数据从 PyObject 复制到浮点数 *
- 使用浮点数和双精度数的非常小数字的数学
- 使用英特尔内联函数将打包的 8 位整数乘以浮点数向量
- 如何在 c++ 中将小数点后两位数的浮点数分配给另一个浮点数
- 返回浮点数的小数位数
- txt 文件中浮点数的最大和最小值
- 为什么 std::cout 打印浮点数、双精度和长双精度到相同的小数精度?
- 将浮点数转换为无符号字符数组并打印出来
- 如何将时间字符串 (M:SS) 转换为浮点数
- 如何将浮点数(*)[6]转换为浮点**类型?
- C++将浮点数乘以分数
- 如何将浮点数转换为uint8_t?
- 将字符串转换为浮点数或整数,而无需使用内置函数(如 atoi 或 atof)
- 如何在C++(Arduino)中将浮点数组转换为字节数组
- 在数学上将浮点数四舍五入到 N 位小数
- 定义浮点数的值特征
- 如何访问特征矢量矩阵<浮点数、2、1 >