Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a shorter way to forward declare a class in a namespace?

Tags:

I can forward declare a function in a namespace by doing this:

void myNamespace::doThing();

which is equivalent to:

namespace myNamespace
{
  void doThing();
}

To forward declare a class in a namespace:

namespace myNamespace
{
  class myClass;
}

Is there a shorter way to do this? I was thinking something along the lines of:

class myNamespace::myClass;
like image 454
Kieveli Avatar asked Sep 02 '09 16:09

Kieveli


People also ask

Can you forward declare a namespace?

There is no forward declaration of namespace.

How do I create a forward class declaration?

In C++, classes and structs can be forward-declared like this: class MyClass; struct MyStruct; In C++, classes can be forward-declared if you only need to use the pointer-to-that-class type (since all object pointers are the same size, and this is what the compiler cares about).

Can you forward declare base class?

A base class MUST be declared (not forward declared) when being declared as a based class of another class. An object member MUST be declared (not forward declared) when being declared by another class, or as parameter, or as a return value.

How do you forward a declaration function in C++?

To write a forward declaration for a function, we use a function declaration statement (also called a function prototype). The function declaration consists of the function header (the function's return type, name, and parameter types), terminated with a semicolon. The function body is not included in the declaration.


2 Answers

No, however with a little reformatting

namespace myNamespace { class myClass; }

isn't much worse than

class myNamespace::myClass;
like image 182
morechilli Avatar answered Sep 28 '22 03:09

morechilli


I've wanted to do the same thing before - it's not allowed. A namespace member must be declared in a namespace-body. They can only be "referred to" using the scope resolution operator.

See 3.3.5 "Namespace scope" in the standard.

Entities declared in a namespace-body are said to be members of the namespace, and names introduced by these declarations into the declarative region of the namespace are said to be member names of the namespace.

and

A namespace member can also be referred to after the :: scope resolution operator (5.1) applied to the name of its namespace or the name of a namespace which nominates the member’s namespace in a using-directive;

like image 37
Michael Burr Avatar answered Sep 28 '22 05:09

Michael Burr