Assigning Namespaces in C ++

I have a little confusion about namespaces. Here is what I know. Usually, if you have namespaces like this in code

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

Now using the following code

 using namespace foo::gfoo; 

you can directly access the apple class without having to foo::gfoo::apple namespace in front of the class as such foo::gfoo::apple .

Now I have seen in some code examples, for example

 namespace qi = boost::spirit::qi 

then in the methods it is used as

 void someMethod() { using qi::char_ } 

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

+6
source share
4 answers

It allows you to smooth out one (usually complex) namespace of your choice.

For instance:

namespace fs = boost::filesystem;

... means you could call ...

fs::exists( myFilePath );

... without the need for writing effort ...

boost::filesystem::exists( myFilePath );

... everytime.

This is mainly for convenience.

+15
source

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

* I use the very fuzzy way available here. After using the directive, characters in the used namespace are added at the level where the current namespace and the used namespace hierarchies are encountered. The search will begin with the current namespace, as always, and then move outward, when it hits a common point in the hierarchy, it will find characters from the namespace that would otherwise have to be qualified.

+4
source

The goal is to create an alias that is easier to enter and read.
There is already a question about namespace aliases here , so duplication is possible.

+1
source

Every time you see the name of a long ass (or any expression in general), this is the possibility of typos or even easily missed intentional differences. To use fairly recent terminology, the qi alias declaration is DRY in action.

+1
source

All Articles