Reputation: 4845
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.
Upvotes: 10
Views: 3381
Reputation: 361402
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.
Upvotes: 7
Reputation: 208343
The correct syntax, as Nawaz mentions already is:
B<> b;
The reason is that B
is the template and B<>
is the instantiation of the template with the default argument A
. But you need the <>
to differentiate when you want an instantiation.
Upvotes: 1
Reputation: 98358
Because you have to say that B
is a template:
B<> b;
Even when you don't want to specify any of the arguments.
Upvotes: 0