Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursive data structure with variant

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.

like image 424
Dess Avatar asked Apr 09 '17 17:04

Dess


Video Answer


1 Answers

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.

like image 67
Vittorio Romeo Avatar answered Oct 09 '22 21:10

Vittorio Romeo