How to modify template type to be unsigned?

82 Views Asked by At
template<class T>
void foo(T s)
{
    unsigned T x = -1;
    //...
}

{
   int x = 129;
   foo(x);
}

How can I modify template type to be unsigned? I know that this is bad practice due to the fact that not everything can be declared unsigned, but in special cases it makes sense.

I do not want to pass the modified type as a template argument. I want to modify the type in the function body itself.

1

There are 1 best solutions below

0
Brian61354270 On

You can use std::make_unsigned to retrieve the unsigned type corresponding to an integral type.

#include <type_traits>

static_assert(
    std::is_same_v<
        unsigned int, 
        std::make_unsigned_t<int>
    >
);

Do note that your program will be ill-formed / exhibit undefined behavior if the template argument T isn't one of the enumerated valid types that std::make_unsigned accepts.