Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple namespace declaration in C++

Tags:

Is it legal to replace something like this:

namespace foo {    namespace bar {       baz();    } } 

with something like this:

namespace foo::bar {    baz(); } 

?

like image 517
Robert Mason Avatar asked Aug 28 '10 02:08

Robert Mason


People also ask

Can you have multiple namespace?

You can have the same name defined in two different namespaces, but if that is true, then you can only use one of those namespaces at a time. However, this does not mean you cannot use the two namespace in the same program. You can use them each at different times in the same program.

What is multiple namespace?

A namespace is a logical container in which all the names are unique; that is, a name can appear in multiple namespaces but cannot appear twice in the same namespace. A namespace is, literally, a space in which to store some names.

How many namespaces are there in C?

In addition, C also partitions a program's identifiers into four namespaces. Identifiers in one namespace, are also considered different from identifiers in another.

Can you declare two namespaces with the same name?

Absolutely nothing, as far as you avoid to use the using namespace <XXX>; directive. As David Vandevoorde said, the “fully qualified name” (the standard term for him “complete name”) is different, while you have to prefix the name with, <namespace>::, and compiler can make the difference between both.


2 Answers

You can combine namespaces into one name and use the new name (i.e. Foobar).

namespace Foo { namespace Bar {     void some_func() {         printf("Hello World.");     } }}  namespace Foobar = Foo::Bar;  int main() {     Foobar::some_func(); } 
like image 140
skimobear Avatar answered Sep 21 '22 06:09

skimobear


Pre C++17:

No, it's not. Instead of a bunch of indented nested namespaces, it's certainly valid to put them on the same line:

namespace Foo { namespace Bar { namespace YetAnother {     // do something fancy } } } // end Foo::Bar::YetAnother namespace 

C++17 Update:

You can now nest namespaces more cleanly in C++17:

namespace Foo::Bar::YetAnother {   // do something even fancier! } 
like image 30
NuSkooler Avatar answered Sep 21 '22 06:09

NuSkooler