如何在C++中获得无符号等价的整数类型?

Ale*_*x B 7 c++ templates

有没有办法在C++中获得有符号整数类型的无符号等价(相同大小)?我在想:

template<typename T>
struct get_unsigned { };

template<>
struct get_unsigned<int> {
    typedef unsigned int type;
};

...

template<typename T>
void myfunc(T val) {
    get_unsigned<T>::type u = std::abs(val);
    ...
}
Run Code Online (Sandbox Code Playgroud)

我正在寻找标准库或Boost中的现有解决方案,除非它是少数几行,否则我不想自己动手.

Jam*_*lis 8

Boost.TypeTraits具有make_unsigned:

type:如果T是无符号整数类型,则与T相同,如果T是有符号整数类型,则为相应的无符号类型.否则,如果T是枚举或字符类型(char或wchar_t),那么无符号整数类型的宽度与T相同.

如果T有任何cv限定符,那么它们也会出现在结果类型中.

来源不仅仅是少数几行.

  • 不出所料,它被添加到 C++11 中的 stdlib 中,作为“std::make_unsigned”:http://www.cplusplus.com/reference/type_traits/make_unsigned/ (2认同)