1

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)
{
    ...
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
FacundoGFlores
  • 7,858
  • 12
  • 64
  • 94
  • Possible duplicate of *[Can function default template parameter be put before non-default ones?](http://stackoverflow.com/questions/11684954/can-function-default-template-parameter-be-put-before-non-default-ones)*. – Peter Mortensen Jun 23 '15 at 22:05

3 Answers3

5

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, or
  • there was an overload of foo taking just a const vector<T>&?
sehe
  • 374,641
  • 47
  • 450
  • 633
2

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.

zch
  • 14,931
  • 2
  • 41
  • 49
0

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) ?

Derrick Rice
  • 155
  • 7