Eric Tabellion
Eric Tabellion

Reputation: 11

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. Here is an example of 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. Ideally I would be able to forward-declare a type in the qualified namespace ::nm like this:

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). 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 ?

Upvotes: 1

Views: 188

Answers (3)

legalize
legalize

Reputation: 2253

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? There's no way for the compiler to know.

Upvotes: 0

SergeyA
SergeyA

Reputation: 62583

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.

Upvotes: 0

cdonat
cdonat

Reputation: 2822

Because the C++ standard says so.

Upvotes: 3

Related Questions