Tuesday, August 4, 2009

Unnamed namespace vs. static keyword

Language: C++

An unnamed namespace definition behaves as if it were replaced by


namespace unique { }
using namespace unique;
namespace unique {namespace-body}


The `unique' name here is guarranteed to be unique, among all translation units. You can put virtual anything into an unamed namespace, and they are exposed to the current module only.

You can also forward declare a function, and later define it, like this:


namespace { int f(int); }

namespace { int f(int a) { /* definition here */ }


And the standard proceeds to claim (paragraph 7.3.1.1.2)


The use of static keyword is deprecated when declaring objects in a namespace scope; the unnamed namespace provides a superior alternative.


Unfortunately I did not see things in this way. namespace is a great feature, however, static is quite obvious. Consider:


static int helper1(int, int, int);

...



This is quite straightforward, and takes less space. In a unnamed namespace, you need two additional lines, and the whole block is not clear to the first reader.

Yes static can't apply on enum and types. That is true. But since unnamed namespace always resides in a .cpp file, not .h file, what is the use of this feature?

Somehow I believe that the standard committee has overstepped on this issue. The statement should not be in the standard as it is more like a personal opinion.