C++ 中的命名空间别名
众所周知,向命名空间 std 添加声明/定义会导致未定义的行为。此规则的唯一例外是模板专业化。
那么下面的“黑客”呢?
#include <iostream>
namespace std_
{
void Foo()
{
std::clog << "Hello World!" << std::endl;
}
using namespace std;
}
int main()
{
namespace std = std_;
std::Foo();
}
就标准而言,这真的是明确定义的吗?当然,在这种情况下,我实际上没有向命名空间 std 添加任何内容。我测试过的每个编译器似乎都很乐意接受这一点。
在有人发表类似“你为什么要这样做?”之类的评论之前——这只是为了满足我的好奇心……
It is widely known that adding declarations/definitions to namespace std
results in undefined behavior. The only exception to this rule is for template specializations.
What about the following "hack"?
#include <iostream>
namespace std_
{
void Foo()
{
std::clog << "Hello World!" << std::endl;
}
using namespace std;
}
int main()
{
namespace std = std_;
std::Foo();
}
Is this really well-defined as far as the standard is concerned? In this case, I'm really not adding anything to namespace std
, of course. Every compiler I've tested this on seems to happily swallow this.
Before someone makes a comment resembling "why would you ever do that?" -- this is just to satisfy my curiosity...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
只要您不在全局声明区域中,就可以将
std
重新定义为别名:由于您在
main()
中定义了别名,因此它会隐藏全局std
名称。这就是为什么它可以工作,应该可以工作,并且根据标准来说完全没问题。您没有向std
命名空间添加任何内容,这种“黑客”只会让代码的人类读者感到困惑。Redefining
std
as an alias is okay, as long as you are not in the global declarative region:Since you define the alias in
main()
, it shadows the globalstd
name. That's why this works, should work, and is perfectly fine according to the standard. You're not adding anything to thestd
namespace, and this "hack" only serves to confuse the human reader of the code.在
main
内部,在命名空间别名定义之后,std
引用std_
命名空间的别名std
。 “通常的”std 命名空间是隐藏的,就像函数局部变量隐藏同名的全局变量一样。Inside
main
, after the namespace alias definition,std
refers to the aliasstd
for thestd_
namespace. The "usual"std
namespace is hidden, much as a function local variable would hide a global variable with the same name.您没有向
std::
添加任何内容。您要添加到std_::
,然后声明一个名为std::
的别名。我从来不知道有一条规则不能添加到
std::
中。这是正确的吗?如果是这样,我猜测该规则的存在只是为了保留命名空间以供将来扩展。因此,如果您确实想增强std::
,则实际上不必破解任何内容。如果您知道不允许这样的事情的编译器,有人会发帖...
You're not adding anything to
std::
. You're adding tostd_::
, then declaring an alias namedstd::
.I never knew that there is a rule you can't add to
std::
. Is that correct? If so, I'm guessing that the rule only exists to reserve the namespace for future expansion. So you really don't have to hack anything if you really want to augmentstd::
.Someone post if you know of a compiler that does NOT allow such a thing...