c++namespacesexplicit-implementation

C++ - Explicit & Implicit Namespace Implementation Differences


I have a question about namespaces if someone can enlighten me :D

I don't know if the title is right, I hope so xD

Code in the ".cpp" file is called the Implementation of the Namespace and the code in ".h" file is called the Declaration of the Namespace? right? :/

Anyway, my Question is:

there is any difference by Explicit or Implicit Implementation of Namespace Members (in the ".cpp" file)?

I mean, let's suppose I have this namespace in "MyNamespace.h":

namespace MyNamespace {

    void fun_one(int a);

    void fun_two(int b);

}

There is any difference if in "MyNamespace.cpp" I do this (Implicit Implementation):

namespace MyNamespace {

    void fun_one(int a){
        // CODE HERE...
    }

    void fun_two(int b){
        // CODE HERE...
    }

}

Or this (Explicit Implementation):

void MyNamespace::fun_one(int a){
    // CODE HERE...
}

void MyNamespace::fun_two(int b){
    // CODE HERE...
}

?

Thanks you so much :D

Have a Nice day & a nice coding! (:


Solution

  • In general, there is no difference between the 2 versions you have shown, and you can use whichever one you prefer.

    For what it's worth, here's one case where it differs slightly:

    namespace A 
    { 
      struct S{};
      S f();        // declare f
    }
    

    and then:

    namespace A 
    {
      S f() { return S{}; }   // define f, ok
    }
    

    is fine, but the following is not:

    S A::f() { return S{}; }
    

    since S is used before the introduction of namespace A. This can be fixed by doing:

    A::S A::f() { return S{}; }
    

    or

    auto A::f() -> S { return S{}; }