c++ - 将 C++ 模板类型 T 修改为 "long T"?

标签 c++ templates types

有什么方法可以将乘法返回的精度加倍(以避免溢出)?

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'。

这是一个普遍的问题。我正在通过内部使用 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++ - 将 C++ 模板类型 T 修改为 "long T"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15283607/

相关文章:

c++ - 在运行时设置 vector 类型

c++ - 构造函数调用子类

c++ - G++ 为未使用的模板特化生成代码?

c++ - 不简单,从 char[8] 转换 long long

c++ - 无法在 Visual Studio 中打开源文件 "SDKDDKVer.h"

c++ - 使用 new 运算符初始化数组

haskell - Haskell 中表达式的类型

.net - 将字典从一种类型转换为另一种类型

c++ - 返回 C++ 函数最后一个参数的通用包装器

c++ - 在 C++ 中为泛型实现线性探测