Search code examples
c++functiontemplatesstandardsoverload-resolution

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


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)
{}

Solution

  • 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.