Default template function argument

Viewed 105

With reference to the following code:

#include <iostream>
#include <variant>
#include <limits>

using namespace std;

template < bool bitwise = false, typename T>
// template <typename T,  bool bitwise = false>  
// ^ wont work! error: no matching function for call to 'func<true>(int, int)'

bool func(T a, T b) {
    if constexpr(bitwise) {
        return a & b;
    }
    else {
        return a && b;
    }
}
int main()
{
    cout << func(7,1) << endl;
    cout << func<true>(7,1) << endl;
}

Why do I have to specify the argument bitwise first in the template list ? Compiler can deduce T from the function arg so why does bitwise need to be the first one in this case?

Wandbox: https://wandbox.org/permlink/xtB2jhmNfBh7IoJz

1 Answers

It's because of this call:

cout << func<true>(7,1) << endl;

This instantiates the template with true as its first (and only) template parameter.

When instantiating a template, any explicit template parameters get assigned to the initial parameters in the template declaration and any remaining parameters must be deducible. This pretty much leaves the given order of template parameters (in the template declaration) as the only order that will work.

Related