Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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".

like image 998
Nic Avatar asked Feb 06 '23 07:02

Nic


1 Answers

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.

like image 168
skypjack Avatar answered Apr 27 '23 02:04

skypjack