1)template <class T = int, class U = double> //compiles
2)template <class T, class U =double> //compiles
3)template <class T = int, class U> //fails
Why does 1 and 2 compile whereas 3 does not?
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.
Which parameter is legal for non-type template? Explanation: 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.
For the same reason why:
void f(int = 0, int);
fails.
There is no way to use 3rd version default parameter:
template<class T = int, class U> class B { ... };
B<, short> var; // ??? no such syntax
(3)
is ill-formed because
C++03 [Section 14.1/11
] says
If a template-parameter has a default template-argument, all subsequent template-parameters shall have a default template-argument supplied.
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