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.)
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.
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.
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.
C++ Templates: Templates with Multiple Parameters | C++ Tutorials for Beginners #65.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With