7

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

2

4 Answers 4

22

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");
4

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.

1
  • +1 but perhaps you could mention that ADL ignores using directives? Commented Apr 14, 2013 at 17:32
1

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.

1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.