Reputation: 8108
Why does this function give me an error:
template < typename T >
T foo( T s = 0, const vector < T > &v)
{
...
}
error: default argument missing for parameter 2 of ‘template summable sum(summable, const std::vector&)’
And why doesn't the following?:
template < typename T >
T foo( const vector < T > &v, T s = 0)
{
...
}
Upvotes: 1
Views: 167
Reputation: 15278
If argument has a default value, than all following arguments need to have default value as well.
Rationale is given in other answers, so I'll give you a quote from C++11 standard:
8.3.6 Default arguments [dcl.fct.default]
4 (...) In a given function declaration, each parameter subsequent to a parameter with a default argument shall have a default argument supplied in this or a previous declaration or shall be a function parameter pack.
Upvotes: 2
Reputation: 155
Arguments with defaults need to be the last arguments. In the first, you have s with a default of 0, then v with no default. You cannot have an argument with no default following an argument with a default.
How would you call such as argument using its defaults? foo(/*default*/,vector)
?
Upvotes: 0
Reputation: 392833
Optional arguments must be the last. I.e. non-optional arguments cannot follow an optional one.
How would you call
T foo( T s = 0, const vector < T > &v)
with just a v
, and no s
?
How would the compiler spot this if
s
and v
had the same type, orfoo
taking just a const vector<T>&
?Upvotes: 5