Defining namespaced member vs free functions without qualification

前端 未结 2 2026

I sometimes declare classes in nested namespaces and when it comes to defining their member functions, I prefer not to have to qualify each one with these nested namespace name

相关标签:
2条回答
  • 2021-01-27 09:50

    When you define a member-function, the compiler realizes that it is a member-function that must belong to a previously declared class, so it looks that class up, as specified in Section 9.3.5 of the standard:

    If the definition of a member function is lexically outside its class definition, the member function name shall be qualified by its class name using the :: operator. [Note: a name used in a member function definition (that is, in the parameter-declaration-clause including the default arguments (8.3.6), or in the member function body, or, for a constructor function (12.1), in a mem-initializer expression (12.6.2)) is looked up as described in 3.4. ] [Example:

    struct X {
        typedef int T; 
        static T count; 
        void f(T); 
    }; 
    
    void X::f(T t = count) { }
    

    The member function f of class X is defined in global scope; the notation X::f specifies that the function f is a member of class X and in the scope of class X. In the function definition, the parameter type T refers to the typedef member T declared in class X and the default argument count refers to the static data member count declared in class X. ]

    Basically, what you are doing is fine. However, there is another (preferable) way to cut down on the clutter when using nested namespaces, or namespaces with long names (or both) - define an alias:

    namespace short_name = averylong::nested::namespacename;
    
    0 讨论(0)
  • 2021-01-27 10:11

    Perhaps I'm getting this wrong but if you have:

    // example.h
    namespace SomeNamespace
    {
        class SomeClass
        {
        public:
            void someMemberFunction();
        };
    
        void someFreeFunction();
    };
    

    You can also simply write:

    #include "example.h"
    
    // example.cpp
    namespace SomeNamespace
    {
        void SomeClass::someMemberFunction()
        {
        }
    
        void someFreeFunction()
        {
        }
    }
    
    0 讨论(0)
提交回复
热议问题