Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get unsigned equivalent of an integral type in C++?

Tags:

c++

templates

Is there a way to get an unsigned equivalent (same size) of a signed integral type in C++? I'm thinking along the lines of:

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);
    ...
}

I'm looking for an existing solution in the standard library or Boost and prefer not to roll my own unless it's a handful of lines.

like image 386
Alex B Avatar asked Mar 16 '10 01:03

Alex B


1 Answers

Boost.TypeTraits has make_unsigned:

type: If T is a unsigned integer type then the same type as T, if T is an signed integer type then the corresponding unsigned type. Otherwise if T is an enumerated or character type (char or wchar_t) then an unsigned integer type with the same width as T.

If T has any cv-qualifiers then these are also present on the result type.

The source is much more than a handful of lines.

like image 127
James McNellis Avatar answered Nov 13 '22 04:11

James McNellis