QPaysTaxes QPaysTaxes - 1 year ago 66
C++ Question

How can I forward declare a type I'm going to create with typedef?

For example, take this snippet of code:

class Foo;
class Something {
Foo *thing;
typedef std::vector<Something> Foo;

This doesn't compile, because
is already a type when the
is hit. However, I think it shows my use case; I have cyclical dependencies and need one to fulfill the other, but (currently) one of the things is typedef'd. I'd prefer not to write something like

class Foo {
std::vector<Something> inside;

because then I need to remember the
in every
. I'd also like to avoid writing a wrapper around
, because it'd be a lot of boilerplate.

How can I forward declare a type which I'm defining with a
Alternatively, how can I resolve my problem of cyclical dependencies without using one of the solutions above? Is it possible at all?

Note that I'm not asking "How can I
with a type that hasn't been declared yet". I'm asking "How can I use
to define a previously-declared type".

Answer Source

Forward declare the class instead:

class Something;
typedef std::vector<Something> Foo;
class Something { Foo *thing; };

If you are using C++11 revision or greater, use an using declaration in place of a typedef:

class Something;
using Foo = std::vector<Something>;
class Something { Foo *thing; };

And that's all.