[英]Why can't I forward-declare a type in a qualified namespace in C++?
I am trying to avoid including an auto-generated header (outside of my control), from inside my own headers. 我试图避免在自己的标头内部包含自动生成的标头(控件之外)。 I therefore need to forward-declare a type
Type
that lives inside a namespace nm
, which itself lives in the global namespace. 因此,我需要向前声明一个驻留在名称空间
nm
的类型Type
,该类型本身位于全局名称空间中。 Here is an example of MyHeader.h
: 这是
MyHeader.h
的示例:
// My project defines two levels of nested namespaces
namespace foo { namespace bar {
namespace nm { struct Type; }
...
} }
Unfortunately this defines the new namespace foo::bar::nm
and forward-declares the type foo::bar::nm::Type
, which is not what I want. 不幸的是,这定义了新的命名空间
foo::bar::nm
并向前声明了foo::bar::nm::Type
,这不是我想要的。 Ideally I would be able to forward-declare a type in the qualified namespace ::nm
like this: 理想情况下,我可以像这样在合格的命名空间
::nm
声明类型:
namespace foo { namespace bar {
namespace ::nm { struct Type; }
...
} }
My compiler complains I cannot use a qualified namespace here (using Intel ICC15 with C++11 settings). 我的编译器抱怨我不能在此处使用合格的名称空间(将Intel ICC15与C ++ 11设置一起使用)。 This forces me to put all such forward declarations at the beginning:
这迫使我在开始时就将所有这些前瞻性声明放在首位:
namespace nm { struct Type; }
namespace foo { namespace bar {
...
} }
In my case, this is inconvenient because I need to forward-declare many types and would prefer to do so alongside definitions of my own in various scattered places in my header. 在我的情况下,这很不方便,因为我需要前向声明许多类型,并且更愿意在标头中各个分散的地方与自己的定义一起声明。 A workaround could be to constantly be "closing" and "re-opening" my nested namespace, which is not ideal.
解决方法可能是不断“关闭”和“重新打开”我的嵌套名称空间,这并不理想。
Why can't I forward-declare a type in a qualified namespace ? 为什么我不能在限定名称空间中向前声明类型?
因为C ++标准是这样说的。
There is no real reason I know of. 我没有真正的原因。 This is just not supported, probably, no one needed it and no one ever requested it.
只是不支持此功能,可能没有人需要它,也没有人要求它。 I see the benefit in your particular case, but since the forward declarations are expected to be provided in a separate file, you'd be better off by simply creating your own
*_fwd.h
with all the forward declarations inside it in the single namespace. 我看到了在您的特定情况下的好处,但是由于预期将在单独的文件中提供前向声明,因此,最好通过在单个名称空间中创建带有所有前向声明的自己的
*_fwd.h
来更好。 。
You can't because it's ambiguous. 您不能因为它含糊不清。 If you wrote:
如果您写了:
extern int foo::bar;
Are you forward declaring an int
named bar
in namespace foo
, or are you forward declaring an int
named bar
inside the class foo
? 你向前声明一个
int
名为bar
的命名空间foo
,或者是你前进的声明int
命名bar
里面的类foo
? There's no way for the compiler to know. 编译器无法知道。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.