5

Consider the following "code":

struct T
{
    T();
    static int x;
};

T::T::T::T::T::T()
{
}

int T::x;

int main()
{
    T t1;
    T::T t2;
    T* p=static_cast<T::T::T::T*>(&t1);
    T::T::T::T::T::x=5;
}

It compiles with both g++ from 4.7 to 8 and clang++ from 3.5 to 6 without any errors or relevant warnings with -pedantic-errors. Apparently, class name followed by scope resolution operator can be repeated without affecting meaning of the class type being named — as if the class is nested inside itself.

Is it a bug in compilers? Or is the C++ language really defined in such a way that it tolerates such abuse?

If it's really standard-conforming C++ code, is there any rationale for allowing this, or is it just to simplify wording of the Standard?

Ruslan
  • 18,162
  • 8
  • 67
  • 136
  • VS2017 is fine with `T::T::T::T::T::T() {}` but not with any of the other odd cases you've shown here. Edit : It's also fine with `T::T::T::T::T::x=5;`. It seems it's fine when used to ultimately indicate a member but not to indicate the type itself. – François Andrieux Jul 30 '18 at 15:08
  • 1
    doesn't compile with recent version of clang or gcc – Tyker Jul 30 '18 at 15:13
  • 1
    https://stackoverflow.com/questions/25549652/why-is-there-an-injected-class-name – geza Jul 30 '18 at 15:23

0 Answers0