For example, take this snippet of code:
class Foo;
class Something {
Foo *thing;
};
typedef std::vector<Something> Foo;
This doesn't compile, because Foo
is already a type when the typedef
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 inside
in every my_foo.inside.some_method()
. I'd also like to avoid writing a wrapper around std::vector<Something>
, because it'd be a lot of boilerplate.
How can I forward declare a type which I'm defining with a typedef
? 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 typedef
with a type that hasn't been declared yet". I'm asking "How can I use typedef
to define a previously-declared type".
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With