As a namespace alias and an alias-based extension of the original namespace
I have a current problem in C ++:
I have a namespace for a given external library. I didn't like the name of this external namespace, so I did the following:
namespace mynamespace = othernamespace;
and that works great if I want to say the following:
mynamespace::foo(...);
but I found that I needed a special function to convert the values ββfound in othernamespace
to values ββfound in an external library. I have defined the function like this:
Y xToY(mynamespace::X x);
I realized that I only wanted to use this function in context mynamespace
, and I still didn't like using the namespace name for othernamespace
, so I thought simply: I would do the following:
namespace mynamespace = othernamespace;
namespace mynamespace{
Y xToY(mynamespace::X x);
}
however I am getting the following compiler error telling me this is not possible:
myheader.h:13:11: error: namespace alias 'mynamespace' not allowed here, assuming 'othernamespace'
and hence it doesn't compile. Note. I am currently using C ++ 14. I would like to know if it is possible to extend this namespace using my alias name for the namespace othernamespace
.
source to share
Nope. Unfortunately this is not possible. The rule from [namespace.def] explicitly excludes aliases:
In the named-namespace definition, the identifier is the name of the namespace. If the identifier in a lookup (3.4.1) refers to a namespace name (but not a namespace alias) that was entered in the namespace in which the named-namespace definition appears or that was entered in a member of the embedded namespace of that namespace, the namespace definition extends the previously declared namespace. Otherwise, the identifier is entered as a namespace name in the declarative scope in which the named-namespace definition appears.
You cannot expand a namespace by aliases, you can only expand a namespace by the name of the original namespace.
source to share
Do this by creating a new namespace, not an alias:
// external namespace
namespace othernamespace {
struct X {};
void foo(X& x) {};
}
// my namespace
namespace mynamespace
{
using namespace othernamespace; // equivalent to import * from othernamespace
}
int main()
{
mynamespace::X x;
foo(x);
}
source to share