【问题标题】:Creating a value constant that depends on the template type创建一个依赖于模板类型的值常量
【发布时间】:2014-03-29 06:26:05
【问题描述】:

我想创建一个 C++ 模板函数,该函数具有不同的常量,这些常量会根据模板类型的选择在实现中使用。

#define FLOAT_EPSILON       (0.000001f)
#define DOUBLE_EPSILON      (0.00000000000001)

template <class T> void func(T params)
{
    const T epsilon = ???? // either FLOAT_EPSILON or DOUBLE_EPSILON depending on T
    // do some calculations using epsilon
}

template void func(float params);
template void func(double params);

虽然我想了一些半途而废的方法,但我不知道如何做到最好。你能帮忙吗?

【问题讨论】:

  • 使用std::numeric_limits怎么样?
  • numeric_limits 看起来是一种可能性,尽管那时我正在使用预定义的值,而不是针对特定数值应用程序调整的我自己的值,尽管我想我可以适当地缩放它们并且接受给定的比率。
  • Denis,你能举个例子说明如何使用 decltype 来解决这个问题吗?
  • 我发现T my_epsilon = std::numeric_limits&lt;T&gt;::epsilon(); 效果很好。

标签: c++ templates types conditional constants


【解决方案1】:

您可以使用帮助模板来选择 epsilon。

template <typename T> struct EpsilonChooser;

template <> struct EpsilonChooser<float>
{
    float const value = 0.000001f;
};

template <> struct EpsilonChooser<double>
{
    double const value = 0.00000000000001;
};

template <class T> void func(T params)
{
    const T epsilon = EpsilonChooser<T>::value;
    // do some calculations using epsilon
}

【讨论】:

    【解决方案2】:

    R-Sahu 解决方案将转换为 C++14 中的变量模板,演示 here

    template <typename T> constexpr T epsilon;
    
    template <> constexpr float  epsilon<float>  = 0.001f;
    template <> constexpr double epsilon<double> = 0.000001;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-02
      • 1970-01-01
      • 1970-01-01
      • 2022-01-14
      相关资源
      最近更新 更多