Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning namespaces in C++

I have a little confusion regarding namespaces. Here is what I know. Normally if you have namespaces such as this in the code

namespace foo
{ 
   namespace gfoo
   {
       class apple
       {..};
   }
}

Now by using the following code

using namespace foo::gfoo;

you could directly access the class apple without going through the trouble of typing the namespace before the class as suchfoo::gfoo::apple.

Now I have seen in some code examples like

namespace qi = boost::spirit::qi

then in methods it is used as

void someMethod()
 {
   using qi::char_
 }

Now my question is what is the purpose of doing something like namespace qi = boost::spirit::qi

like image 728
MistyD Avatar asked Apr 14 '13 17:04

MistyD


4 Answers

It allows for the aliasing of one (typically complex) namespace to one of your choosing.

For example:

namespace fs = boost::filesystem;

... means that you could then call ...

fs::exists( myFilePath );

... without having to go through the effort of writing out ...

boost::filesystem::exists( myFilePath );

... every time.

It's mainly for convenience.

like image 94
Jimmy Thompson Avatar answered Oct 08 '22 12:10

Jimmy Thompson


The using directive makes the names in the used namespace available *, while the namespace alias creates another name for a namespace, it only provides a different (hopefully shorter or simpler) name for an existing namespace, but you will need to still qualify or employ a using directive to make it available.

* I am using available in a very fuzzy way here. After the using directive, the symbols in the used namespace are added at the level where the current namespace and the used namespace hierarchies meet. Lookup will start with the current namespace as always and then move outwards, when it hits the common point in the hierarchy it will find the symbols from the namespace that would otherwise need to be qualified.

like image 25
David Rodríguez - dribeas Avatar answered Oct 08 '22 11:10

David Rodríguez - dribeas


The purpose is to create alias that is easier to type and read.
There is already question about namespace aliases here so this is possibly duplicate.

like image 32
alexrider Avatar answered Oct 08 '22 11:10

alexrider


Every time you see a long-ass name (or any expression generally), it's an opportunity for typos or even easy-to-miss intentional differences. To use fairly recent terminology, declaring the qi alias is the DRY principle in action.

like image 29
jthill Avatar answered Oct 08 '22 12:10

jthill