在我的代码中,我有很多模板算法,其中模板类型必须是 float (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++ - 如何根据模板类型定义浮点常量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59032270/