Why does the default argument not work in a template function?

Viewed 132
struct A {};

template<typename T>
void f(int n, T m = 3.14159)
{}

int main()
{    
    f(8, A{}); // ok
    f(8); // error: no matching function for call to 'f'
}

See online demo

Why does the default argument not work in a template function?


EDIT: I also tried following, and wonder why it didn't work as well.

void g(int, auto = 3.14159)
{}
2 Answers

Default function arguments don't affect template argument deduction.

You need a default argument for the template parameter too: typename T = double.


As for void g(int, auto = 3.14159), there seems to be no way to fix it.

In the first case, you gave a value for the second function parameter at the call site, which the compiler could use to deduce the type of the second template argument, which then let it determine which version of the template to instantiate and call.

In the second case, you gave the compiler no information about the type for the second template argument, so it cannot use the template to instantiate the function, and so there is no function with that signature available to call.

The compiler will not use a parameter's default value to deduce a template argument type for that parameter (keep in mind that potentially many choices for the type T could accept a double as a default value).

Related