Correct way to define C++ namespace methods in .cpp file

I'm using version 4 (below) because it combines most of the advantages of version 1 (terseness of the resoective definition) and version 3 (be maximally explicit). The main disadvantage is that people aren't used to it but since I consider it technically superior to the alternatives I don't mind.

Version 4: use full qualification using namespace aliases:

#include "my-header.hpp"
namespace OI = outer::inner;
void OI::Obj::method() {
    ...
}

In my world I'm frequently using namespace aliases as everything is explicitly qualified - unless it can't (e.g. variable names) or it is a known customization point (e.g. swap() in a function template).


5 years later and i thought I'd mention this, which both looks nice and is not evil

using ns1::MyClass;

void MyClass::method()
{
  // ...
}

Googles C++ Style Guide dictates your version 1, without indentation though.

Googles C++ Style Guide for namespaces


Version 2 is unclear and not easy to understand because you don't know which namespace MyClass belongs to and it's just illogical (class function not in the same namespace?)

Version 1 is right because it shows that in the namespace, you are defining the function.

Version 3 is right also because you used the :: scope resolution operator to refer to the MyClass::method () in the namespace ns1. I prefer version 3.

See Namespaces (C++). This is the best way to do this.