Bre*_*ust 11 c++ templates types
有没有办法加倍乘法返回的精度(以避免溢出)?
template<class T> class MyClass {
T multiply (T a, T b) { return a * b; }
}
Run Code Online (Sandbox Code Playgroud)
就像是:
long T multiply (T a, T b) { return a * b; }
Run Code Online (Sandbox Code Playgroud)
因此,无论是'int','long'还是'double',都会从multipal返回'long int','long long'或'long double'.
这是一个普遍的问题.我正在通过内部使用double来解决它.但我的问题是,是否有任何机制可以将类型提升为C++中的"长"变体?
And*_*owl 14
一种可能的解决方案是定义您自己的类型特征:
template<typename T>
struct add_long { typedef T type; };
template<>
struct add_long<int> { typedef long int type; };
template<>
struct add_long<double> { typedef long double type; };
template<>
struct add_long<long int> { typedef long long int type; };
// And so on...
Run Code Online (Sandbox Code Playgroud)
这就是你在课堂上使用它的方法:
template<class T>
class MyClass {
public:
typedef typename add_long<T>::type longT;
longT multiply (longT a, longT b) { return a * b; }
};
Run Code Online (Sandbox Code Playgroud)
这是一个小测试:
#include <type_traits>
int main()
{
MyClass<int> m;
auto l = m.multiply(2, 3);
static_assert(std::is_same<decltype(l), long int>::value, "Error!");
}
Run Code Online (Sandbox Code Playgroud)