【发布时间】:2020-02-18 19:49:58
【问题描述】:
在学习 C++ 时,我决定编写一个简单的模板化二叉搜索树 (bst),但遇到了以下问题:我希望能够构造一个 bst,方法是向它传递一个像 @987654322 这样的左值@ 和像 T &&val 这样的右值。同样,我希望能够插入左值和右值。所以我最终得到了很多我不喜欢的重复代码:
/// 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} {}
};
还有:
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) 和 find(T &&val)..提供重载吗?
所以我的问题是是否有一种方法可以组合这些重载或任何 其他方式来删除这个重复的代码?
我读到了reference collapsing rules,但我不确定我是否可以在这里使用这个概念。
也欢迎任何其他想法或建议。
【问题讨论】:
-
小注:
inline在constexpr函数的情况下是多余的。
标签: c++ overloading code-duplication rvalue lvalue