如何根据模板类型定义浮点常量?
How can I define floating point constants depending on template type?
在我的代码中,我有很多模板算法,其中模板类型必须是浮点数(float
、double
或long double
(。其中一些算法需要默认的 epsilon 值。例:
template <typename FloatType>
bool approx(FloatType x1, FloatType x2)
{
const FloatType epsilon; // How can I set it ?
return abs(x2 - x1) < epsilon;
}
我该如何定义它?我尝试了以下内容,它被 gcc 接受,但它不是标准的(并且在 C++11 中无效(。我知道在 C++11 中是可能的,但我必须与 c++03 兼容。
template <typename FloatType>
struct default_epsilon
{};
template <>
struct default_epsilon<float>
{
static const float value = 1.0e-05f;
};
template <>
struct default_epsilon<double>
{
static const double value = 1.0e-10;
};
template <>
struct default_epsilon<long double>
{
static const long double value = 1.0e-12l;
};
// Then, I use it like that :
template <typename FloatType>
bool approx(FloatType x1, FloatType x2)
{
return abs(x2 - x1) < default_epsilon<FloatType>::value;
}
// or that
bool approx(FloatType x1, FloatType x2, FloatType epsilon = default_epsilon<FloatType>::value)
{
return abs(x2 - x1) < epsilon;
}
如果你不想使用std::numeric_limits<FloatType>::epsilon()
,我认为你可以按照评论中的建议去做:初始化类定义之外的static
成员。
你可以写:
#include <cmath>
template <typename FloatType>
struct default_epsilon
{};
template <>
struct default_epsilon<float>
{
static const float value;
};
template <>
struct default_epsilon<double>
{
static const double value;
};
template <>
struct default_epsilon<long double>
{
static const long double value;
};
template <typename FloatType>
bool approx(FloatType x1, FloatType x2)
{
return std::abs(x2 - x1) < default_epsilon<FloatType>::value;
}
在您的.cpp文件中的某个地方:
const float default_epsilon<float>::value = 1.0e-05f;
const double default_epsilon<double>::value = 1.0e-10;
const long double default_epsilon<long double>::value = 1.0e-12l;
它应该可以解决问题。
使用传统的 C++ 转换运算符重载
class MyEpsilon
{
public:
operator float() {return 1.0e-05f;};
operator double() { return 1.0e-10; };
operator long double() { return 1.0e-12l; };
};
template<class T>
class MyTest {
public:
T DoSome() {
MyEpsilon e;
return T(e);
}
};
相关文章:
- 如何根据模板类型定义浮点常量?
- 自定义Vector2D类中的浮点错误
- 将节点数组(可变长度)转换为常量浮点**以调用opencv.calcHist
- 将常量浮点*转换为垫子
- 定义浮点等价关系的标准方法
- 如果浮点范围较大,是否总是定义浮点往返行为?
- 浮点常量不精确的警告
- 模板元编程和浮点常量系数
- 如何编写浮点常量
- 为什么在C++17中使用十六进制浮点常量
- 如何在模板中定义浮点常量.避免在运行时强制转换
- 如何在C++中定义自定义浮点格式(类型)
- 浮点常量的编译时转换
- C++浮点常量总是存储在静态内存中吗
- 声明浮点常量时出错
- 如何初始化类内浮点常量
- C/ c++中浮点常量的紧凑无损表示
- 在MATLAB中用十六进制浮点常量解析文件
- 模板化代码中的浮点常量
- IEEE 浮点与自定义浮点性能