为什么由 extern 声明引入的名称只允许来自最内部的封闭命名空间?如果没有,它会带来什么复杂性?还是仅仅因为这部分标准是从 C 标准复制而来的,没有命名空间?
Please see the respective part of the standard
编辑:
一个可以方便使用的示例场景:使用 x
在函数模板中 f
在命名空间 ns
, 其中 x
在全局命名空间中的某处定义,并且不希望在所有翻译单元中引入(在函数定义之外)#include header f
.
namespace ns
{
template <typename> void f()
{
// extern int ::x; // ill-formed
extern int x; // refers to ns::x, which is not the case :(
++x;
}
}
最佳答案
Why is it forbidden to qualify name in extern declaration?
因为没有意义。
假设您要使用
foo::bar
而在命名空间 foo:::baz
.有两种情况foo::bar
是可见的。那么你不需要重新声明它。只需使用名称,如果需要则限定。 foo::bar
不可见。那么你不能首先在除 foo
之外的任何命名空间中声明它。 . Why are names introduced by an extern declaration only allowed to come from the innermost enclosing namespace?
他们不是。它们可能来自全局命名空间,这是
extern
的主要用例。 .另一个用例是前向声明一个稍后将在同一命名空间中定义的函数,我想这是甚至允许此类相同命名空间声明的唯一原因。 extern
没太大必要在这些用例之外。提前申报foo::bar
从内部 foo::baz
太困惑且容易出错。
关于c++ - 为什么禁止在 extern 声明中限定名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58749393/