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

标签 c++ templates constants c++03

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

相关文章:

c++ - 为什么 sizeof(std::string) 只有八个字节?

c++ - 在对象中存储引用会产生奇怪的结果

C++ lambda 引用

c++ - Eclipse 中的新 .h 文件产生一个#define 常量

c++ - 当编译时参数未知时创建 execv 参数数组

c++ - Scott Meyers 第二版关于在 Effective C++ 中实现 nullptr 的一些问题?

c++ - 右值引用模板推导

C++ 在数组中存储具有不同模板的相同类

java - 从 Java 对象类到 C++

c++ - 我如何使用一个非常量值来实例化一个类的多个对象?