I have this code:
struct A{};
template<class T = A>
struct B {
void foo() {}
};
B b; //Error: missing template arguments before 'b'
//Error: expected ';' before 'b'
//More errors
b.foo()
If I make foo()
as a template function with the same template 'signature', the compiler doesn't complain about not specifying the template arguments:
struct A {};
struct B {
template<class T = A>
void foo() {}
};
B b; //OK
b.foo()
So why do I need to specify an argument for a template class with a default parameter, but not for a template function? Is there some subtlety I am missing?
The reason is because of template argument deduction failure for sure. But I want to know why.
The correct syntax is this (demo):
B<> b;
The default argument A
is assumed for the class template B
. The <>
part tells the compiler that B
is a class template and asks it to take the default parameter as the template argument to it.