Nawaz Nawaz - 2 months ago 6
C++ Question

Superiority of unnamed namespace over static?

How are unnamed namespaces superior to the

static
keyword?

Answer

You're basically referring to the section $7.3.1.1/2 from the C++ Standard,

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

Unnamed namespace is superior to static keyword, primarily because the keyword static applies only to the variables declarations and functions, not to the user-defined types.

The following code is valid in C++

   //legal code
   static int sample_function() { /* function body */ }
   static int sample_variable;

But this code is NOT valid:

   //illegal code
   static class sample_class { /* class body */ };
   static struct sample_struct { /* struct body */ };

So the solution is, unnamed-namespace, which is this,

   //legal code
   namespace 
   {  
        class sample_class { /* class body */ };
        struct sample_struct { /* struct body */ };
   }

Hope it explains that why unnamed-namespace is superior to static.

Also, note that use of static keyword is deprecated when declaring objects in a namespace scope (as per the Standard).