I am not sure how it is different from just surrounding the implementation with namespace namespace_name { }
This is to put your own code within a namespace, as opposed to using some name from another namespace. Say you write a draw
function inside the Graphics
namespace -- to do this, you wrap draw
's code in namespace Math { void draw() { /* some code */ } }
and to use it you'd do Graphics::draw
. However, when you need to use a function, say, gamma
in the Math
namespace (which you didn't write), you've to call it Math::gamma
for the compiler to know where to search for gamma
. Alternatively, you may use shorthand, to drop the Math::
part.
I guess this is just for using shorthand names?
Yes, that's to allow identifiers from some namespace to be used without the qualifier. There are two ways to do it.
- Using directive: Use all names in a namespace without qualification (e.g.
using namespace Math;
)
- Using declaration: Use only some specified names without qualification (e.g.
using Math::gamma
) -- this is usually better than the former.
However, both are encouraged to be used only in an implementation/source file and not in a header to avoid some sources which may have its own copy of gamma
and don't want to use Math::gamma
, but since you've it in the header, it'll lead a clash of the names. More details on "using namespace" in c++ headers.