2010-03-16 42 views
7

有没有办法在C++中得到一个带符号整型的无符号等价(相同大小)?我沿线的思考:如何获得在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); 
    ... 
} 

我正在寻找在标准库或加速现有的解决方案,并且不希望推出自己的,除非它是线的屈指可数。

回答

8

Boost.TypeTraits具有make_unsigned

类型:如果T是一个无符号的整数类型,那么相同类型为T,如果T是一个符号整型那么相应的无符号类型。否则,如果T是枚举类型或字符类型(char或wchar_t),则使用与T宽度相同的无符号整数类型。如果T具有任何cv限定符,则这些也存在于结果类型中。

The source远不止于少数几行。

+0

这已被添加到C++ 11中的stdlib,可以预见为'std :: make_unsigned':http://www.cplusplus.com/reference/type_traits/make_unsigned/ – 2016-08-29 12:19:40