Class declaration in same scope as using declaration compiles in GCC but not MSVS

流过昼夜 提交于 2019-11-28 01:07:39

问题


Is the following program well-formed according to the c++ standard?

namespace X { class A; }

namespace Y { using X::A; class A {}; }

int main() {}

I'm getting different results with different compilers:

  • gcc compiles it without errors.
  • visual c++ gives error C2888: 'X::A': symbol cannot be defined within namespace 'Y'

I don't find any rule in the c++ standard that my program violates.

If the program is well-formed, why does visual studio give an error?

If the program is not well-formed, what rule in the c++ standard did it violate and why doesn't gcc give an error?

I'm not trying to make my program compile. I'm just trying to find out if it is well-formed according to the c++ standard and why the two compilers I tested behave differently.


回答1:


I believe the program is ill formed. [basic.scope.declarative]/4 says:

Given a set of declarations in a single declarative region, each of which specifies the same unqualified name,

— they shall all refer to the same entity, or all refer to functions and function templates; or

— exactly one declaration shall declare a class name or enumeration name that is not a typedef name and the other declarations shall all refer to the same variable or enumerator, or all refer to functions and function templates; in this case the class name or enumeration name is hidden

The two declarations of unqualified name A refer to different entities, both of which are classes.

(Interestingly, neither GCC 6.0 nor Clang 3.7 seem to diagnose it that way. Both accept the code as written (not diagnosing the declaration of two distinct classes with the same name). If you add X::A a; to the body of main, then Clang complains about the incomplete type of X::A.)




回答2:


Not too sure but you can try something like this :

namespace X { class A; }

namespace Y 
{
  class X::A {}; 
}

int main() 
{
  return 0;
}


来源:https://stackoverflow.com/questions/31220154/class-declaration-in-same-scope-as-using-declaration-compiles-in-gcc-but-not-msv

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!