Search code examples
c++c++11namespaces

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


Solution

  • It's called a namespace alias. It allows you to shorten and rename an existing namespace to make it easier to read. For example:

    // original
    boost::filesystem::exists("/tmp/file.txt");
    
    // aliased
    namespace fs = boost::filesystem;
    fs::exists("/tmp/file.txt");