有没有可能制作一个 constexpr 树?
Is it possible to make a constexpr tree?
我想构建一个具有固定数量的子树结构的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>());
}
请注意,这会生成很多类型。
相关文章:
- 当一个值是非常量但用常量表达式初始化时使用constexpr
- 有没有可能制作一个 constexpr 树?
- 为什么 std::launder 是一个 constexpr 函数?
- 我可以定义一个 constexpr 匿名/未命名变量吗?
- 是否已经有一个 constexpr std::bit_cast 与 g++ 一起使用
- 为什么我不能声明一个 constexpr 本地,而一个 const 一个工作?
- 我可以使用 constexpr 函数声明一个静态数组吗?
- 我可以在模板参数中声明一个 constexpr lambda 吗?
- 用另一个 constexpr 数组对成员数组进行大括号初始化
- 有没有办法构造一个 constexpr 函数来获取双精度的位表示
- 是否可以为 AVR 编写一个 constexpr 舍入函数?
- 如何以静态方式使用另一个 constexpr 数组初始化一个数组
- 为什么在这种情况下它不是一个 constexpr?
- 将对静态存储 cstyle 数组的引用从 constexpr 函数传递到另一个 constexpr 函数
- 如何使用 std::copy 将一个 constexpr 数组复制到另一个 constexpr 数组
- 初始化一个constexpr std ::数组,其大小的n维std ::数组
- 我什么时候可以确定一个 constexpr 全局变量会像 C 宏一样被"forgotten"?
- 将一个 constexpr 数组初始化为其他两个 constexpr 数组的总和
- 一个 constexpr 比 const 更"constant"吗?
- POD结构体的值初始化是一个constexpr