Why isn't referencing other parameters in default values allowed?

http://ideone.com/nuQAcK
1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <vector>

void f(std::vector<int> const &v, std::vector<int>::const_iterator it = v.end())
{
}

int main()
{
	f({});
}
prog.cpp:4:73: error: local variable ā€˜v’ may not appear in this context
 void f(std::vector<int> const &v, std::vector<int>::const_iterator it = v.end())
                                                                         ^
Why is this not allowed? (I mean, what is the reasoning for defining the standard this way?)

Thankfully (hopefully) in C++14/C++17 we will have a unified way to represent end iterators without an instance of the container, but currently I just have to hope my implementation accepts a default-constructed iterator as an end iterator.
Last edited on
It would be possible in the language design, but it currently is not, because v is a local variable, and you may not reference local variables in default argument expressions.

The way to get around it is simply overloading the function, though frankly you are mixing things a little.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <vector>

template <typename Iterator>
void print( Iterator begin, Iterator end )
  {
  while (begin != end)
    {
    std::cout << *begin++ << " ";
    }
  std::cout << std::endl;
  }

template <typename Container>
inline
void print( const Container& v )
  {
  print( v.begin(), v.end() );
  }

int main()
  {
  print <std::vector <int> > ( { 2, 3, 5, 7, 11 } );
  }

Hope this helps.
Thanks, so it's just not been considered.

But just fyi, my actual use case has nothing to do with iterating the container ;)
> so it's just not been considered.

It has been considered.

The order of evaluation of function arguments is unspecified. Consequently, parameters of a function shall not be used in a default argument, even if they are not evaluated. - IS
Ah, thanks, that makes much more sense now. I guess it would be extra work for the compiler to ensure that dependent arguments are evaluated before non-dependent ones.
Topic archived. No new replies allowed.