PYA
PYA

Reputation: 8636

Default template function argument

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

Upvotes: 2

Views: 107

Answers (1)

Sam Varshavchik
Sam Varshavchik

Reputation: 118445

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.

Upvotes: 4

Related Questions