A class-specifier whose class-head-name contains a nested-name-specifier may not be appear within a class; only within the enclosing namespace
From [class]/11:
If a class-head-name contains a nested-name-specifier, the class-specifier shall refer to a class that was previously declared directly in the class or namespace to which the nested-name-specifier refers, or in an element of the inline namespace set of that namespace (i.e., not merely inherited or introduced by a using-declaration), and the class-specifier shall appear in a namespace enclosing the previous declaration. In such cases, the nested-name-specifier of the class-head-name of the definition shall not begin with a decltype-specifier.
In your failing example, A:: is the nested-name-specifier and A::B { ... } is the class-specifier. The criteria
[...] the class-specifier shall appear in a namespace enclosing the previous declaration.
is not fulfilled. Particularly, note that the class-specifier contains the class-head, which in turns contains a class-head-name, which in turn contains, optionally, a nested-name-specifier, as well as (non-optionally) a class-name. If the nested-name-specifier is present, [class]/11 applies, in which case (as emphasized above) the requirement of where the class-specifier is allowed applies; particularly, not being allowed nested within a class.
Thus your program is ill-formed; Clang is right.
We may note that Clang accepts the program if the class-specifier for B appears at namespace scope (enclosing the previous in-class declaration):
class Outer {
public:
class A {
public:
class B;
};
};
class Outer::A::B {
public:
int foo=0;
};
Finally, note that [class.nest]/3 mentions defining nested class in-class of the class in which they were declared, as well as at namespace scope of the enclosing namespace:
If class X is defined in a namespace scope, a nested class Y may
be declared in class X and later defined in the definition of class
X or be later defined in a namespace scope enclosing the definition
of class X. [_ Example:_
class E { class I1; // forward declaration of nested class
class I2; class I1 { }; // definition of nested class }; class
E::I2 { }; // definition of nested class
— end example ]
which allows your first example:
class A {
public:
class B;
};
class A::B {
public:
int foo=0;
};
to be re-factored as
class A {
public:
class B {
public:
int foo=0;
};
};
or
class A {
public:
class B; // forward declaration
// ...
class B {
public:
int foo=0;
};
};
but there is no conflict here with [class]/11, which specifically governs the allowed grammar for when a class-head-name contains a nested-name-specifier.