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
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With