ume*_*ebe 10 c++ templates function literals specialization
我正在尝试找到一个解决方案,在模板类方法中有不变的数字文字.我正在制作一些与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...
*/
return x;
}
template <>
float SomeClass<float>::getValue()
{
return 0.5f;
}
template <>
double SomeClass<double>::getValue()
{
return 0.5;
}
Run Code Online (Sandbox Code Playgroud)
这个不需要为特定类型多次编写相同的方法,但需要为方法内部需要使用的每个"幻数"设置很多getValue()方法.
还有另一种"更优雅"的方式来解决这个问题吗?
您无需担心这一点 - 使用 0.5,如果类型为 float,编译器仍会将其优化为与使用 0.5f 相同的值。
这有点啰嗦,但您可能想阅读我的答案中的“支持多态性的其他机制”部分:Polymorphism in c++
对于整个函数中浮点常量的更一般用法 - 特别是在比较和表达式中 - 值得阅读下面提到的链接 bluemess....