Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Alias a namespace and extend the original namespace based on the alias

I have the 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 this following:

namespace mynamespace = othernamespace;

and this works fine if I want to say do the following:

mynamespace::foo(...);

but I found that I needed to have a special function to convert values found in othernamespace to values found in an external library. I defined a function the following way:

Y xToY(mynamespace::X x);

I realized I only wanted to use this function in the context of mynamespace, and I still didn't like using the namespace name for othernamespace so I thought simple, I would do the following:

namespace mynamespace = othernamespace;

namespace mynamespace{
    Y xToY(mynamespace::X x);
}

however I get the following compiler error telling me that this can't be done:

myheader.h:13:11: error: namespace alias 'mynamespace' not allowed here, assuming 'othernamespace'

and thus it doesn't compile. Note I'm currently using c++14. I would like to know if it is possible for me to extend this namespace using my alias name for the namespace othernamespace.

like image 282
Krupip Avatar asked May 05 '17 15:05

Krupip


2 Answers

Nope. It's unfortunately not possible. The rule, from [namespace.def], explicitly excludes aliases:

In a named-namespace-definition, the identifier is the name of the namespace. If the identifier, when looked up (3.4.1), refers to a namespace-name (but not a namespace-alias) that was introduced in the namespace in which the named-namespace-definition appears or that was introduced in a member of the inline namespace set of that namespace, the namespace-definition extends the previously-declared namespace. Otherwise, the identifier is introduced as a namespace-name into the declarative region in which the named-namespace-definition appears.

You cannot extend a namespace by alias, you can only extend a namespace by the original namespace name.

like image 74
Barry Avatar answered Sep 24 '22 07:09

Barry


Do it by building a new namespace, rather than 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);
}
like image 39
Richard Hodges Avatar answered Sep 25 '22 07:09

Richard Hodges