c++ - 模板类中 float 和 double 文字的函数特化

标签 c++ function templates literals specialization

我正在尝试找到一种解决方案,以便在模板类方法中使用常量数字文字。我正在制作一些与 float 或 double 类型一起使用的数学模板类。问题在于文字因数据类型而异(例如,“0.5f”表示 float ,“0.5”表示 double )。到目前为止,我想出了两个解决方案。第一个的一些假设代码:

template <typename T>
class SomeClass
{
    public:
        T doSomething(T x);
};

template <>
float SomeClass<float>::doSomething(float x)
{
    float y = 0.5f;
    /*
     * Do computations...
    */
    return x;
}

template <>
double SomeClass<double>::doSomething(double x)
{
    double y = 0.5;
    /*
     * Do computations...
    */
    return x;
}

上述方法强制为它所使用的每种类型重写整个方法。

另一种方法:

template <typename T>
class SomeClass
{
    public:
        T doSomething(T x);

    private:
        T getValue();
};

template <typename T>
T SomeClass<T>::doSomething(T x)
{
    T y = getValue();
    /*
     * Do computations...
    */
    return x;
}

template <>
float SomeClass<float>::getValue()
{
    return 0.5f;
}

template <>
double SomeClass<double>::getValue()
{
    return 0.5;
}

这个不需要为特定类型多次编写相同的方法,但需要为每个需要在方法内部使用的“魔数(Magic Number)”编写很多 getValue() 方法。

是否有另一种“更优雅”的方法来解决这个问题?

最佳答案

假设实际上有必要在两个特化中使用不同的值(例如,对于 0.5 和 0.5f 就没有必要),那么输入的代码就会少很多:

template <typename T>
class SomeClass
{
  public:
    T doSomething(T x);

  private:
    static const T magic_number_1;
};

template <typename T>
T SomeClass<T>::doSomething(T x)
{
  T y = magic_number_1;
  /* 
   * Do computations...
  */
  return x;
}

template <>
const float SomeClass<float>::magic_number_1 = 0.5f;

template <>
const double SomeClass<double>::magic_number_1 = 0.5;

关于c++ - 模板类中 float 和 double 文字的函数特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11088059/

相关文章:

c++ - 环回抓包

c# - 如何使用函数的错误列表返回结果

PHP 定义一个变量,如果它没有传递给函数

c++ - 对 `void sort::swap<int>(int*, int, int)' 的 undefined reference

c++ - unsigned long long 算术

c++ - 指针互转换:派生到base的reinterpret_cast

c++ - 将可变参数模板粘合到可变参数函数

php - 在 Wordpress 中隐藏管理菜单项

c++函数模板编译错误 "‘containerType’不是模板”

c++ - 由于成员函数与参数类型的名称冲突,模板构造函数在 MSVC 中失败