【发布时间】:2022-12-14 08:54:55
【问题描述】:
我正在创建一个类似 b+ 树的数据结构,不同之处在于每个节点级别能够保存不同类型的值(用于缓存目的)并且具有不同数量的子节点。
例如。:
- root-node 最多包含 8 个 level1-node 子节点和 Struct1 的值,
- level1-node 最多包含 16 个 level2-node 子节点和 Struct2 的值,
- level2-node 最多包含 32 个叶节点子节点和 Struct 3 的值,
- 叶节点持有 StructLeaf 的值。
我不需要在运行时更改树结构,所以我想使用模板来配置它。 我期望上面示例的实例化看起来像这样:
Tree<StructLeaf, <8, Struct1>, <16, Struct2>, <32, Struct3>>()
和这样的模板定义,这不是实际的代码,只是我认为它可能看起来像这样:
// variadic template recursion 'entrypoint'
template<
typename TLeafData, // do I have to set leaf data before variadic template, even if it is of different structure?
<int TChildrenSize, typename TData>... TChildNodes> // list of pairs of nodes configurations, how to make it a variadic of pairs?
>
class Node;
// template recursion body
template<
typename TLeafData, //same as before
<int TChildrenSize, typename TData> TNode, // values for the current node, how to define a pair?
<int TChildrenSize, typename TData>... TChildNodes> // same as before
>
class Node {
TNode.TData data; // how to access TNode.TData?
std::array<Node<TLeafData, TChildNodes...>, TNode.TChildrenSize> children; // how to pass TChildNodes and access TNode.TChildrenSize?
}
// template recursion end
template<
typename TLeafData, //same as before
<> // empty template to stop recursion, how to define it?
>
class Node {
TLeafData data;
}
我看到如何在没有 TData 的情况下,仅使用 ChildrenSize,通过使用 int 的递归模板来制作这个结构,但我也想知道是否可以或如何将数据类型添加到模板?
我尝试为此使用模板的模板,但看起来它是用于传递对之外的另一个用例,因为我找不到访问内部模板值的方法。
template<template<int A, typename B> typename C>
class AClass {
C.B data; // type B is unaccessable
}
【问题讨论】:
标签: c++ templates data-structures