有没有可能制作一个 constexpr 树?

Is it possible to make a constexpr tree?

本文关键字:一个 constexpr 有可能      更新时间:2023-10-16

我想构建一个具有固定数量的子树结构的constepxr树结构,这些子结构可能是也可能不是树。该结构将能够回答以下问题:"此树中的索引 2 中是否存在节点?

理想情况下,我想写这样的东西:

struct Tree {
std::array<std::optional<Tree>, 5> children; // 5 children max for each tree
};

不幸的是,Tree引用自身无法编译。

我错过了什么,或者有什么方法可以解决这个限制吗?你知道一个解决类似问题的实现吗?

以下内容适用于 C++17。这应该是可能的,但在以前的版本上要烦人得多:

#include <tuple>
struct no_node{};
template<class... ChildTrees>
struct Tree {
using tuple_t = std::tuple<ChildTrees...>;
tuple_t children;
template<int N>
static constexpr bool has_child() {
if constexpr(N >= sizeof...(ChildTrees)) {
return false;
} else {
return !std::is_same_v<std::tuple_element_t<N, tuple_t>, no_node>;
}
}
};

int main()
{
Tree<> leaf;
Tree<no_node, decltype(leaf)> right;
static_assert(!leaf.has_child<0>());
static_assert(right.has_child<1>());
static_assert(!right.has_child<0>());
static_assert(!right.has_child<2>());
}

请注意,这会生成很多类型。