c++ - 如何给命名空间起别名并根据别名扩展原来的命名空间

标签 c++ namespaces c++14

我在 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/

相关文章:

c++ - printf 如何知道 CString 字符数据的地址?

c++ - 如何在命名空间中使用 += 函数

c++ - 从编译时已知的日历日期创建 `std::chrono::time_point`

c++ - "_dyld_start"在我的分析结果中意味着什么?

c++ - 使用 .png 文件的动画 cocos2dx

c# - 在运行时 C# 从不同的命名空间中选择对象?

php - 使用命名空间找不到类

c++ - iterator::operator* 的标准接口(interface)返回的内容多于 T& 和 std::pair

c++ - <chrono> 中的用户定义文字重载

c++ - 提高 QTimer 的准确性