[英]Using a class in a namespace with the same name?
I have to use an API provided by a DLL with a header like this 我必须使用DLL提供的API和这样的标头
namespace ALongNameToType {
class ALongNameToType {
static void Foo();
}
}
Is there a way to use ALongNameToType::ALongNameToType::Foo without having to type ALongNameToType::ALongNameToType each time? 有没有办法使用ALongNameToType :: ALongNameToType :: Foo而不必每次都输入ALongNameToType :: ALongNameToType? I tried using
using namespace ALongNameToType
but got ambiguous symbol errors in Visual Studio. 我尝试使用
using namespace ALongNameToType
但在Visual Studio中出现了模糊的符号错误。 Changing the namespace name or removing it gives me linker errors. 更改命名空间名称或删除它会给我发现链接器错误。
I don't know what's ambiguous, but you can avoid all conflicts with other Foo functions like this: 我不知道什么是不明确的,但你可以避免与其他Foo函数的所有冲突,如下所示:
namespace ALongNameToType {
struct ALongNameToType {
static void Foo();
};
}
typedef ALongNameToType::ALongNameToType Shortname;
int main() {
Shortname::Foo();
}
namespace myns = ALongNameToType;
It seems that you can't alias a class scope like this: 看来你不能像这样对类范围进行别名:
// second ALongNameToType is a class
namespace myns = ALongNameToType::ALongNameToType;
Maybe you could alias the function it self: 也许你可以将它自己的功能别名:
namespace foo
{
class foo
{
public:
static void fun()
{
}
};
}
int main()
{
void (*myfunc)() = foo::foo::fun;
myfunc();
}
using ALongNameToType::ALongNameToType::Foo;
如果你只是想把它用作Foo()
。
There are three ways to use using
. 有三种使用
using
。 One is for an entire namespace, one is for particular things in a namespace, and one is for a derived class saying it doesn't want to hide something declared/defined in a base class. 一个用于整个命名空间,一个用于命名空间中的特定事物,一个用于派生类,表示它不想隐藏在基类中声明/定义的内容。 You can use the second of those:
您可以使用其中的第二个:
using ALongNameToType::ALongNameToType
Unfortunately this isn't working for you (due to the ambiguity of the namespace and the class having the same name). 不幸的是,这对你不起作用(由于命名空间和具有相同名称的类的模糊性)。 Combining this type of using with a previous answer should get rid of the ambiguity:
将这种类型的使用与之前的答案结合起来应该消除歧义:
namespace alntt = ALongNameToType;
using alntt::ALongNameToType;
But once you've renamed the namespace, you really don't need the using
statement (as long as you're comfortable writing the (shortened) namespace every time you use the class: 但是一旦你重命名了命名空间,你真的不需要
using
语句(只要你每次使用该类时都习惯于编写(缩短的)命名空间:
namespace alntt = ALongNameToType;
alntt::ALongNameToType a;
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.