Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making function template parameter unsigned in C++11

In a template function that looks like this:

template<typename T> constexpr T foo(T a, T b) { return /*recursive call*/; }

I am getting a warning about comparing signed vs unsigned (due to comparing against sizeof) which I'd like to eliminate.

Conceptually, one would need something like this:

template<typename T> constexpr T foo(T a, unsigned T b) { ... }
    or
template<typename T> constexpr T foo(T a, std::make_unsigned<T>::type b) { ... }

Unluckily, the first version is not valid C++, and the second version breaks the build because T is not a qualified type when the compiler sees make_unsigned.

Is there is a solution for this that actually works?

(NB: Somehow related to / almost same as Get the signed/unsigned variant of an integer template parameter without explicit traits, though function rather than class (so no typedefs), traits or any feature of C++11 explicitly welcome, and working solution (i.e. not make_unsigned<T>) preferred.)

like image 791
Damon Avatar asked Jul 03 '12 15:07

Damon


People also ask

Can a template be a template parameter?

Templates can be template parameters. In this case, they are called template parameters. The container adaptors std::stack, std::queue, and std::priority_queue use per default a std::deque to hold their arguments, but you can use a different container. Their usage is straightforward.

Can we pass Nontype parameters to templates?

Template classes and functions can make use of another kind of template parameter known as a non-type parameter. A template non-type parameter is a template parameter where the type of the parameter is predefined and is substituted for a constexpr value passed in as an argument.

What does template <> mean in C++?

Templates in c++ is defined as a blueprint or formula for creating a generic class or a function. Generic Programming is an approach to programming where generic types are used as parameters in algorithms to work for a variety of data types.In C++, a template is a straightforward yet effective tool.

Which template can have multiple parameters?

C++ Templates: Templates with Multiple Parameters | C++ Tutorials for Beginners #65.


1 Answers

You forgot a 'typename'

template<typename T>
constexpr T foo(T a, typename std::make_unsigned<T>::type b) { ... }

In C++14 you should be able to write

template<typename T>
constexpr T foo(T a, std::make_unsigned_t<T> b) { ... }

Or you can implement this yourself in C++11:

template<typename T>
using make_unsigned_t = typename std::make_unsigned<T>::type;
like image 112
bames53 Avatar answered Oct 01 '22 18:10

bames53