8

This code

int clash;

struct Foo {
  decltype(clash) clash;
};

compiles silently on clang, but fails to compile on gcc giving the errors

error: declaration of 'int Foo::clash' [-fpermissive]

error: changes meaning of 'clash' from 'int clash' [-fpermissive]

It seems that 2 ingredients are required for the error to arise:

  1. The shadowing must be done by a class member (no problem if it's a function's local scope).

  2. decltype([shadowed name]) must be used in the shadowing scope before the declaration of [shadowing name].

My question is twofold:

  1. Is gcc justified in rejecting this code?
  2. Where does it say so in the standard?
jacg
  • 2,040
  • 1
  • 14
  • 27
  • What about: `int chash[sizeof(clash)];` ? What does different compiler say? I guess it is not to do with C++11 complaint compilers, but how they behave in such cases. – Ajay Oct 31 '14 at 19:30

1 Answers1

10

gcc is correct the program is ill-formed, although this particular violation does not require a diagnostic so clang does not have to provide one.

If we look at the C++11 standard(The closest draft would be N3337) section 3.3.7 Class scope it says:

A name N used in a class S shall refer to the same declaration in its context and when re-evaluated in the completed scope of S. No diagnostic is required for a violation of this rule.

and the next rule says:

If reordering member declarations in a class yields an alternate valid program under (1) and (2), the program is ill-formed, no diagnostic is required.

It makes sense we would want to prevent situations where reordering the declarations in a class give a different program. It is curious whether these two rules are redundant or not.

The section also provides the following example:

enum { i = 1 };

class X {
  char v[i]; // error: i refers to ::i
             // but when reevaluated is X::i
  int f() { return sizeof(c); } // OK: X::c
  char c;
  enum { i = 2 };
};

and if we try this example with gcc (see it live), we get an almost identical error to one your code produces:

 error: declaration of 'i' [-fpermissive]
 enum { i = 2 };
          ^

 error: changes meaning of 'i' from '<anonymous enum> i' [-fpermissive]
 enum { i = 1 };
Community
  • 1
  • 1
Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
  • You cited a _draft_, which means little. I'm showing you how to cite the actual standard, which is authoritative. – Lightness Races in Orbit Nov 01 '14 at 05:17
  • 4
    The drafts "meaning little" is not .. *entirely* true. Their full designation is "Standard **Working** Draft", and as such they are quite a bit more than 'just a draft'. Looking at [this question](http://stackoverflow.com/questions/14184203/changes-between-c-standard-working-drafts), it is clear they get refined gradually. – Jongware Nov 02 '14 at 13:49