具有变体的递归数据结构
Recursive data structure with variant
在 C++17 中,是否可以声明这样的东西以便编译:
struct Foo;
using Var = std::variant<Type1, Type2, Foo>; // uses Foo
struct Foo {
std::vector<Var> member; // uses Var
}
这是一个简化的示例,但我需要这样的递归数据结构。
是的,这是可能的。您所需要的只是某种可以与 不完整类型 一起正常工作的 indirection/container。例如:std::unique_ptr
、std::vector
和 std::map
.
struct Foo
{
std::variant<int, float, std::vector<Foo>> _data;
};
int main()
{
Foo a{std::vector<Foo>{Foo{}, Foo{}}};
}
需要间接访问以避免定义 "infinite size" 变体。以下是有关该主题的一些学习资源:
David Sankel 的 “Variants: Past, Present, and Future" CppCon 2016 演讲很好地介绍了一般变体,涵盖了 "recursive variants"。
我在 "visiting variants using lambdas pt.2" 文章中简要介绍了 "recursive variants"。
在 C++17 中,是否可以声明这样的东西以便编译:
struct Foo;
using Var = std::variant<Type1, Type2, Foo>; // uses Foo
struct Foo {
std::vector<Var> member; // uses Var
}
这是一个简化的示例,但我需要这样的递归数据结构。
是的,这是可能的。您所需要的只是某种可以与 不完整类型 一起正常工作的 indirection/container。例如:std::unique_ptr
、std::vector
和 std::map
.
struct Foo
{
std::variant<int, float, std::vector<Foo>> _data;
};
int main()
{
Foo a{std::vector<Foo>{Foo{}, Foo{}}};
}
需要间接访问以避免定义 "infinite size" 变体。以下是有关该主题的一些学习资源:
David Sankel 的 “Variants: Past, Present, and Future" CppCon 2016 演讲很好地介绍了一般变体,涵盖了 "recursive variants"。
我在 "visiting variants using lambdas pt.2" 文章中简要介绍了 "recursive variants"。