Can class members be defined outside the namespace in which they are declared?

余生颓废 提交于 2019-12-19 05:13:19

问题


Sometimes I find code like the following (actually some class-wizards create such code):

// C.h
namespace NS {

class C {
    void f();
};

}

and in the implementation file:

// C.cpp
#include "C.h"

using namespace NS;
void C::f() {
  //...
}

All the compilers I tried accept that kind of code (gcc, clang, msvc, compileonline.com). What makes me feel uncomfortable is the using namespace NS;. From my point of view C::f() lives in the global namespace in an environment that has unqualified access to objects living in namespace NS. But in the compiler's opinion void C::f() lives in namespace NS. As all compilers I tried share that point of view they are probably right, but where in the standard is this opinion backed?


回答1:


Yes, the syntax is indeed legal, but no, your function actually does live in the namespace NS. The code you are seeing is actually equivalent to

namespace NS { void C::f() { /* ... } }

or to

void NS::C::f() { /* ... */ }

which may be more similiar to what you are used to.

Because of the using-directive you can omit the NS part not only in calling code, but also in its definition. The Standard has an example that matches your code (after the bold emphasized part):

3.4.3.2 Namespace members [namespace.qual]

7 In a declaration for a namespace member in which the declarator-id is a qualified-id, given that the qualified-id for the namespace member has the form nested-name-specifier unqualified-id the unqualified-id shall name a member of the namespace designated by the nested-name-specifier or of an element of the inline namespace set (7.3.1) of that namespace. [ Example:

namespace A {
  namespace B {
    void f1(int);
  }
  using namespace B;
}
void A::f1(int){ } // ill-formed, f1 is not a member of A

—end example ] However, in such namespace member declarations, the nested-name-specifier may rely on using-directives to implicitly provide the initial part of the nested-name-specifier. [ Example:

namespace A {
  namespace B {
    void f1(int);
  }
}

namespace C {
  namespace D {
    void f1(int);
  }
}

using namespace A;
using namespace C::D;
void B::f1(int){ } // OK, defines A::B::f1(int)

—end example ]

So you may omit the initial part of the nested-name-specifier, but not any intermediate part.



来源:https://stackoverflow.com/questions/25176985/can-class-members-be-defined-outside-the-namespace-in-which-they-are-declared

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