A field name similar to a field type using an unnamed namespace

Consider this sample code:

#include <iostream>

namespace /* unnamed namespace */
{
    struct Foo
    {
        int a;
        int b;
    };
}

struct Boo
{
    Foo Foo; /* field name same as field type */
    int c;
    void print();
};

void Boo::print()
{
    std::cout<<"c = "<<c<<std::endl;
    std::cout<<"Foo "<<Foo.a<<" "<<Foo.b<<std::endl;
}

int main()
{
    Boo boo;
    boo.c=30;
    boo.Foo.a=-21;
    boo.Foo.b=98;
    boo.print();
    return 0;
}

Clang can compile it without errors.

Debian clang version 3.5.0-9 (tags / RELEASE_350 / final) (based on LLVM 3.5.0)

Microsoft cl.exe will compile it without errors. (I do not remember the version. I am using VS 2012)

And GCC: gcc version 4.9.2 (Debian 4.9.2-10):

main.cpp:14:6: error: declaration of ‘{anonymous}::Foo Boo::Foo [-fpermissive]
  Foo Foo; /* field name same as field type */
      ^
main.cpp:5:9: error: changes meaning of ‘Foo’ from ‘struct {anonymous}::Foo’[-fpermissive]
  struct Foo
         ^

What is good compiler behavior? Why can't GCC compile it, but clang and cl.exe? What does the C ++ standard say?

+4
source share
1 answer

Both are correct. According to §3.3.7 / 1

The following rules describe the scope of names declared in classes.

  • [..]

  • N, S, S. .

, gcc clang, -, . .

+4

All Articles