Alex B
Alex B

Reputation: 84812

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

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.

Upvotes: 8

Views: 1396

Answers (2)

jpo38
jpo38

Reputation: 21514

As commented by underscore_d on "James McNellis" answer, one can now use standard std::make_unsigned function: https://cplusplus.com/reference/type_traits/make_unsigned.

Nice when you don't want to use boost for this.

Upvotes: 2

James McNellis
James McNellis

Reputation: 355049

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.

Upvotes: 8

Related Questions