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.
Like function default arguments, templates can also have default arguments. For example, in the following program, the second parameter U has the default value as char.
Can default arguments be used with the template class? Explanation: The template class can use default arguments.
A template parameter is a special kind of parameter that can be used to pass a type as argument: just like regular function parameters can be used to pass values to a function, template parameters allow to pass also types to a function.
The following are legal for non-type template parameters:integral or enumeration type, Pointer to object or pointer to function, Reference to object or reference to function, Pointer to member.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With