在学习 C++ 时,我决定编写一个简单的模板化二叉搜索树(bst)并遇到以下问题:我希望能够构造通过向其传递一个左值来实现 bst,例如const T &val
和一个像这样的右值T &&val
。同样我希望能够insert左值和右值。所以我最终得到了很多我不喜欢的重复代码:
/// copy constructor
explicit inline constexpr binary_search_tree(const T &val)
: _root{std::make_unique<binary_search_tree_node>(val)} {}
/// move constructor
explicit inline constexpr binary_search_tree(T &&val)
: _root{std::make_unique<binary_search_tree_node>(std::move(val))} {}
对于构造函数,其中binary_search_tree_node
是私人成员binary_search_tree
然后还必须提供复制和移动构造函数:
struct binary_search_tree_node {
T value;
std::unique_ptr<binary_search_tree_node> left;
std::unique_ptr<binary_search_tree_node> right;
// prohibit creation of tree_node without value
inline constexpr binary_search_tree_node() = delete;
/// copy constructor
explicit inline constexpr binary_search_tree_node(const T &val)
: value{val}, left{nullptr}, right{nullptr} {}
/// move constructor
explicit inline constexpr binary_search_tree_node(T &&val)
: value{std::move(val)}, left{nullptr}, right{nullptr} {}
};
Also:
inline constexpr void insert(const T &v) {
if (!_root) {
_root = std::make_unique<binary_search_tree_node>(v);
++_size;
} else {
insert(_root, v);
}
}
inline constexpr void insert(T &&v) {
if (!_root) {
_root = std::make_unique<binary_search_tree_node>(std::move(v));
++_size;
} else {
insert(_root, std::move(v));
}
}
用于插入功能。
当我想搜索一个值时,这个列表还在继续:我应该为以下内容提供重载吗?find(const T &val)
and find(T &&val)
..?
所以我的问题是是否有一种方法可以组合这些重载或任何重载
还有其他方法可以删除这个重复的代码吗?
我读到参考折叠规则 https://en.cppreference.com/w/cpp/language/reference#Reference_collapsing但我不确定我是否可以在这里利用这个概念。
任何其他想法或建议也将受到赞赏。