C++ 模板类的树,其中children是std::数组std::unique\u ptr
我的情况如下:C++ 模板类的树,其中children是std::数组std::unique\u ptr,c++,arrays,c++11,unique-ptr,C++,Arrays,C++11,Unique Ptr,我的情况如下: template<size_t Level> class Node { public: Node() { for (size_t i = 0; i < children.size(); i++) children[i].reset(new Node<Level - 1>()); } array<unique_ptr<Node<Level - 1>>
template<size_t Level>
class Node
{
public:
Node()
{
for (size_t i = 0; i < children.size(); i++)
children[i].reset(new Node<Level - 1>());
}
array<unique_ptr<Node<Level - 1>>, 4> children;
};
template<>
class Node<0>
{
};
...
Node<2> root;
模板
类节点
{
公众:
节点()
{
对于(size_t i=0;i
我需要创建一个节点树,其中除最后一个(级别=0)外,每个节点都有4个子节点。我想把孩子们存储在std::unique的std:array
中
我的解决方案是对的还是做错了什么,有更聪明的方法来实现这个结果?我看不出在这里使用模板的价值。树是固定的且大小有限,您可以将其设置为值类型
例如,具有叶节点的4级树包含类型为V
的值:
namespace Tree {
template <typename V>
struct Root {
struct Tier1 {
struct Tier2 {
struct Tier3 {
struct Leaf { V value; };
std::array<Leaf, 4> children;
};
std::array<Tier3, 4> children;
};
std::array<Tier2, 4> children;
};
std::array<Tier1, 4> children;
};
}
从理论上讲,你似乎可以直接使用std::array
@Jarod42,如果不使用指针,我不能有太深的层次。如果这真的是你想要实现的,那没关系。您可能会考虑将<代码> STD::数组改为<代码> STD::tuple < /C> >,如果您要使用这4个孩子中的任何一个的编译时间(非运行时)索引。std::array
在注释中;这不是问题。例如,一个10层深的树,如果没有指针,将消耗大约27MB的自动存储空间,比大多数搁置的实现要大得多。@etouris一个同构的std::tuple
与std::array
相比,没有什么优势,它也可以与std::get
等一起使用。如果链接器中的编译器具有良好的ICF,则代码大小只会在实际存在差异的情况下增加。诚然,除了MSVC和gcc的黄金链接器(上次我检查过)之外,大多数编译器都缺乏ICF支持(相同的comdat折叠)。@Yakk我是否错过了一条关于代码/二进制大小的评论?我想我在你的回答中读了一些关于“复制方法”之类的内容。我在编辑历史中看不到它,所以也许我产生了幻觉。@Yakk我只是对模板的模板表示怀疑。但是,请注意我是如何为LeafValue
添加类型参数的。因为这个对我来说很有意义
std::array<optional<Leaf>, 4> children; };
std::array<optional<Tier3>, 4> children; };
std::array<optional<Tier2>, 4> children; };
std::array<optional<Tier1>, 4> children;
#include <array>
#include <boost/optional.hpp>
namespace Tree {
using boost::optional;
template <typename LeafValue, int level> struct Node;
template <typename LeafValue> struct Node<LeafValue, 3> {
LeafValue value;
};
template <typename LeafValue, int level> struct Node {
std::array<optional<Node<LeafValue, level+1> >, 4> children;
};
template <typename LeafValue> using Root = Node<LeafValue, 0>;
}
int main()
{
Tree::Root<int> a = {
};
}