Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ syntax ambiguity

Tags:

c++

gcc

Consider:

void f(std::pair<bool,bool> terms = std::pair<bool,bool>(1,1)) {}

gcc 4.4 is ok, gcc 4.3 complains error: expected ',' or '...' before '>' token. The fix is:

void f(std::pair<bool,bool> terms = (std::pair<bool,bool>(1,1))) {}

What's the reason? Is it a bug in 4.3?

like image 765
Anycorn Avatar asked Apr 06 '11 21:04

Anycorn


1 Answers

This was a known issue. It thinks that the second comma separates parameter declarations. This comes from the fact that in a class definition, function default arguments are first only tokenized, and then only later parsed when the full class body has been read. As it thus doesn't really parse the default argument, it doesn't notice the comma is really a comma within a template argument list instead.

See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#325 for something to read about it. Cited

The other problem is with collecting the tokens that form the default argument expression. Default arguments which contain template-ids with more than one parameter present a difficulty in determining when the default argument finishes. Consider,

template <int A, typename B> struct T { static int i;};
class C {
  int Foo (int i = T<1, int>::i);
};

The default argument contains a non-parenthesized comma. Is it required that this comma is seen as part of the default argument expression and not the beginning of another of argument declaration? To accept this as part of the default argument would require name lookup of T (to determine that the '<' was part of a template argument list and not a less-than operator) before C is complete. Furthermore, the more pathological

class D {
  int Foo (int i = T<1, int>::i);
  template <int A, typename B> struct T {static int i;};
};

would be very hard to accept. Even though T is declared after Foo, T is in scope within Foo's default argument expression.

like image 103
Johannes Schaub - litb Avatar answered Sep 29 '22 06:09

Johannes Schaub - litb