我正在制作一个类——一个 BST——它可以比较模板化节点,这需要一个比较器,例如 std::less
。
树是这样的:
template<typename T, typename comparator>
class tree
{
private:
comparator compare;
public:
explicit tree (comparator functor);
};
但我似乎找不到应该在我的应用程序中输入哪种模板类型。
tree<int> my_bst (std::less<int>);
error: wrong number of template arguments (1, should be 2)
bst::tree<int> my_bst (std::less<int>);
这是有道理的,因为我的模板类型不完整。
我应该如何分析我的构造函数?
模板的那个属性是什么?因为我只找到了 cppreference 上的 sort
页面.
通常,我可以像这样使用sort
std::vector<int> v;
std::sort(v.begin (), v.end (), std::less<>());
less的特化是怎么推导出来的?我怎样才能复制它?
最佳答案
为了节省您自己和其他只想要默认行为的人,额外的击键告诉编译器比较器的类型您可以默认设置它,然后如果您想要不同的行为则只需指定它.
template<typename T, typename comparator = std::less<T>>
class tree
{
private:
comparator compare;
public:
explicit tree (comparator functor = comparator{});
};
将默认 comparator
到类型std::less<T>
并让您构造类
tree<int> my_bst;
然后,如果你想使用不同的类型,比如 std::greater
, 那么你会使用
tree<int, std::greater<int>> my_bst;
因为你现在拥有它,所以你必须使用
tree<int, std::less<int>> my_bst(std::less<int>{});
^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^
| pass an instance of the comparator to the constructor
|
tell the compiler the type of the comparator
制作tree
使用 std::less<int>
.
至于为什么可以做
std::vector<int> v;
std::sort(v.begin (), v.end (), std::less<>());
std::less
已专门用于 std::less<void>
在 C++14 中,它提供了一个 operator ()
这是模板化的,并将推断传递给它的类型。这意味着 std::less<>
的对象可以比较任何两种类型,只要表达式
decltype(std::forward<T>(lhs) < std::forward<U>(rhs))
在 T
都有效的情况下有效和 U
是 operator ()
的参数类型.
关于c++ - std::less<int> 的正确参数类型是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52598616/