我正在尝试找到一个解决方案,在模板类方法中有不变的数字文字.我正在制作一些与float或double类型一起使用的数学模板类.问题是文字因数据类型而异(例如浮点数为"0.5f",双数字为"0.5").到目前为止,我提出了两个解决方案.第一个假设代码:
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;
}
Run Code Online (Sandbox Code Playgroud)
上面的方法强制为它使用的每种类型重写整个方法.
另一种方法:
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...
*/ …Run Code Online (Sandbox Code Playgroud)