我在 C++ 中遇到了当前的问题:
我有一个给定外部库的 namespace 。我不喜欢这个外部命名空间的名称,所以我做了以下操作:
namespace mynamespace = othernamespace;
如果我想说执行以下操作,这很好用:
mynamespace::foo(...);
但我发现我需要一个特殊的函数来将 othernamespace
中的值转换为外部库中的值。我通过以下方式定义了一个函数:
Y xToY(mynamespace::X x);
我意识到我只想在 mynamespace
的上下文中使用这个函数,而且我仍然不喜欢将命名空间名称用于 othernamespace
所以我想简单,我会做以下事情:
namespace mynamespace = othernamespace;
namespace mynamespace{
Y xToY(mynamespace::X x);
}
但是我收到以下编译器错误,告诉我这无法完成:
myheader.h:13:11: error: namespace alias 'mynamespace' not allowed here, assuming 'othernamespace'
因此它无法编译。注意我目前使用的是 c++14。我想知道我是否可以使用命名空间 othernamespace
的别名来扩展此命名空间。
最佳答案
没有。不幸的是,这是不可能的。来自 [namespace.def] 的规则明确排除了别名:
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.
您不能通过别名扩展命名空间,您只能通过原始命名空间名称扩展命名空间。
关于c++ - 如何给命名空间起别名并根据别名扩展原来的命名空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43808562/