我正在尝试找到一种解决方案,以便在模板类方法中使用常量数字文字。我正在制作一些与 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/