整个类范围内的C ++名称空间别名 [英] 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?
我的解决方案
我发现我不需要为特定的问题使用未命名的命名空间,并且可以简单地做到这一点:
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.
推荐答案
命名空间别名为非法.
仅在名称空间范围或功能范围内的 中允许允许.
Its allowed in only in namespace scope or function scope.
您可以在命名空间范围内创建别名.但这将成为永久别名,也可以从其他文件中使用该别名.但是解决方案很简单:您可以使用 unnamed 命名空间来防止其他文件中看到别名(以及大命名空间中的所有符号).这是可以做到的:
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.
从其他文件看不到别名.编译OtherFile.cpp
时,GCC(4.5.0)说,
The alias is not visible from other files. When compiling OtherFile.cpp
, GCC (4.5.0) says,
'myspace :: abc'尚未声明
'myspace::abc' has not been declared
这证明别名abc
在MyFile.cpp
中仅仅可见.感谢 unnamed 命名空间.
That proves the alias abc
is visible only in MyFile.cpp
. Thanks to unnamed namespace.
演示: http://www.ideone.com/2zyNI (尽管它没有演示OtherFile概念.我无法ideone.com上有多个文件)
Demo : http://www.ideone.com/2zyNI (though it doesn't demonstrate OtherFile concept. I cannot have more than one file at ideone.com)
这篇关于整个类范围内的C ++名称空间别名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!