如何根据模板类型定义浮点常量?

How can I define floating point constants depending on template type?

本文关键字:定义 浮点常量 类型 何根      更新时间:2023-10-16

在我的代码中,我有很多模板算法,其中模板类型必须是浮点数(floatdoublelong 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);
}
};