Devolus
Devolus

Reputation: 22084

C++ Split namespace declarations

I was wondering wether namespaces can be splitted or if a definition of a namespace has to be in a single block. To illustrate what I mean:

namespace test
{
    //declare a bunch of stuff here
    int a;
}

Here we do something else like declaring a class or whatever

class T
{
};

and here continues the namespace from above, extending it

namespace test
{
    //declare a bunch of additional stuff here
    int b;
    T val;
}

In this example the namespace test has been used twice, so does this mean that test is extended by the second defintion? When I used it like this in gcc it works as expected. I can access all variables with test::... as if it were defined in a single namespace. Of course this doesn't make it standard, so I would like to know if this is according to the standard.

I was also surprised that I didn't even get a warning or such. But wouldn't this mean that you can accidently use a name which is already used without begin aware of it thus extending it?

Upvotes: 3

Views: 1371

Answers (2)

taocp
taocp

Reputation: 23634

You can certainly do that, an example is presented in C++11 standard N3485 Section 7.3.3.11

Quoted below.

The entity declared by a using-declaration shall be known in the context using it according to its definition at the point of the using-declaration. Definitions added to the namespace after the using-declaration are not considered when a use of the name is made.

[ Example:

namespace A 
{ 
    void f(int); 
} 
using A::f; // f is a synonym for A::f; 
            // that is, for A::f(int). 
namespace A 
{ 
    void f(char); 
}

void foo() 
{ 
   f(’a’); // calls f(int), 
}         // even though f(char) exists.

void bar() 
{ 
    sing A::f; // f is a synonym for A::f; 
               // that is, for A::f(int) and A::f(char). 
    f(’a’); // calls f(char) 
}

—end example ]

Upvotes: 4

Mats Petersson
Mats Petersson

Reputation: 129374

Yes, you can split the contents of a namespace over several sections.

If you compile using gcc and use -ansi and -pedantic will give you warnings for non-standard code.

A typical use-case of this is of course when you declared a set of things in a header file, and then implement these in a source file.

// header.h

namespace somename
{
   class A
   {
      // stuff goes here 
      void func();
      // more stuff. 
   }
 }

// source.cpp

#include "header.h"

namespace somename
{

   void A::func()
   {
      // whatever A::func() is supposed to do goes here. 
   }
}

Upvotes: 2

Related Questions