问题描述
我有一个tree_node
类和一个tree
类.
template<typename T>
class tree_node
{
public:
tree_node(const std::string& key_, const T& value_)
: key(key_), value(value_)
{
}
private:
T value;
std::string key;
};
template<typename T>
class tree
{
public:
tree() : root(new tree_node<T>("", ???)) { }
private:
tree_node<T>* root;
};
tree_node
在创建时需要T
的实例.如何在???
位置传递它?我可以说T()
,但是只有在T
具有无参数构造函数的情况下,它才有效.我没有tree_node
的无参数构造函数,因为如果T
没有无参数的构造函数,它将无法编译.
tree_node
expects an instance of T
when creating. How can I pass it in the ???
place? I can say T()
, but it will work only if T
has a parameterless constructor. I can't have a parameterless constructor for tree_node
as it won't compile if T
doesn't have a parameterless constructor.
我正在寻找一种设计tree_node
的方法,该方法可以正确保存所有类型,包括指针类型.
I am looking for a way to design tree_node
which can hold all types correctly including pointer types.
修改
尝试各种方法后,我发现boost::optional
在这种情况下很有用.我可以将T value
变成boost::optional<T> value
.这将解决空构造函数问题.因此,我可以有另一个tree_node
的构造函数重载,它只需一个key
.根节点可以使用它.这是正确的方法吗?
After trying various methods, I found that boost::optional
is helpful in this case. I can make the T value
into boost::optional<T> value
. This will solve the empty constructor issue. So I can have another constructor overload of tree_node
which just takes a key
. This can be used by the root node. Is this the correct way to go?
谢谢..
推荐答案
初始根值应为零.如果您推送新节点,您显然会知道价值.
Init root value should be zero. If you push new node you obviously know value.
template<typename T>
class tree
{
public:
tree() : root(0) { }
void push (const std::string& key, const T & t) {
if (root == 0) {
root = new tree_node<T>(key, t);
} else {
// Make complex tree
}
}
private:
tree_node<T>* root;
};
添加
如果使用后缀树,则应制作两种类型的顶点:
If you use suffix tree you should make two types of vertices:
enum NodeType { EMPTY_NODE, VALUE_NODE };
class base_tree_node
{
public:
base_tree_node() :parent(0), left(0), right(0) {}
virtual NodeType gettype() = 0;
protected:
base_tree_node* parent;
base_tree_node* left;
base_tree_node* right;
};
class empty_tree_node : base_tree_node
{
virtual NodeType gettype() { return EMPTY_NODE; }
}
template<typename T>
class tree_node : base_tree_node
{
public:
tree_node(const std::string& key_, const T& value_)
: key(key_), value(value_)
{
}
virtual NodeType gettype() { return VALUE_NODE; }
private:
T value;
std::string key;
};
这篇关于持有泛型类型的实例-C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!