In C++17, is it possible to declare something like this such that it compiles:
struct Foo;
using Var = std::variant<Type1, Type2, Foo>; // uses Foo
struct Foo {
std::vector<Var> member; // uses Var
}
This is a simplified example, but I need a recursive data structure like this.
Yes, it is possible. All you need is some sort of indirection/container that works properly with incomplete types. Examples are: std::unique_ptr
, std::vector
, and std::map
.
struct Foo
{
std::variant<int, float, std::vector<Foo>> _data;
};
int main()
{
Foo a{std::vector<Foo>{Foo{}, Foo{}}};
}
live wandbox example
Indirection is required in order to avoid defining an "infinite size" variant. Here are some learning resources on the topic:
David Sankel's “Variants: Past, Present, and Future" CppCon 2016 talk is a great introduction to variants in general and covers "recursive variants".
I briefly cover "recursive variants" in my "visiting variants using lambdas pt.2" article.
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