将C模板类型T修改为“长T”?

有没有办法加倍乘法返回的精度(以避免溢出)?
template<class T> class MyClass {
     T multiply (T a,T b) { return a * b; }
}

就像是:

long T multiply (T a,T b) { return a * b; }

因此,无论是“int”,“long”还是“double”,都会从乘法中返回“long int”,“long long”或“long double”.

这是一个普遍的问题.我正在使用内部的双重工作.但我的问题是,是否有任何机制来推广一种类型到C的“长”变体?

解决方法

一个可能的解决方案是定义自己的类型特征:
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...

这是你如何在你的班上使用它:

template<class T>
class MyClass {
public:
    typedef typename add_long<T>::type longT;
    longT multiply (longT a,longT b) { return a * b; }
};

这里是一个小小的考验:

#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!");
}

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...