Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
342 views
in Technique[技术] by (71.8m points)

C++ namespace alias in entire class scope

I expected to be able to use a namespace alias in a class declaration but get a compiler syntax error.

struct MyClass
{
    namespace abc = a_big_namespace;
    void fn() {
        abc::test();
    }
};

The only way I can get it to work is to put the alias in every function.

void fn() {
    namespace abc = a_big_namespace;
    abc::test();
}

Additionally I would like to be able to use the alias for function parameters. I haven't found a work-around for that.

void fn(abc::testType tt) {
    abc::test(tt);
}

Is there a way to do what I want?

EDIT: my solution

I found that I didn't need unnamed namespace for my particular problem and can simply do this:

namespace myspace
{
    namespace abc = a_big_namespace;

    struct MyClass
    {
       void fn(abc::testType tt) {
          abc::test(tt);
       }
    };
}

To switch to the other library, which is what my alias namespace refers to I just change the alias. This method even allows me to have the same class in a single file twice, each time refering to a different library. Thanks for all your help.

question from:https://stackoverflow.com/questions/6056047/c-namespace-alias-in-entire-class-scope

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Namespace alias in the class definition is illegal, as specified by the language specification.

Its allowed in only in namespace scope or function scope.

You can make alias at namespace scope. But that will be make permanent alias which can be used from other files as well. But the solution is simple : you can use unnamed namespace to prevent alias (and therefore all symbols from the big namespace) from being visible from other files. This is how it can be done:

//MyFile.cpp
namespace myspace
{ 
    namespace   //this is unnamed namespace
    {
       namespace abc = a_big_namespace;     
    }
    struct MyClass 
    {
      void fn() 
      { 
         abc::test();  //don't worry, this will work!
      } 
    };
}

//OtherFile.cpp

myspace::abc::test(); //error - that means, prevention worked.

The alias is not visible from other files. When compiling OtherFile.cpp, GCC (4.5.0) says,

'myspace::abc' has not been declared

That proves the alias abc is visible only in MyFile.cpp. Thanks to unnamed namespace.

Demo : http://www.ideone.com/2zyNI (though it doesn't demonstrate OtherFile concept. I cannot have more than one file at ideone.com)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...