【问题标题】:What is the correct argument type for std::less<int>?std::less<int> 的正确参数类型是什么?
【发布时间】:2018-10-02 05:21:42
【问题描述】:

我正在创建一个类 -- 一个 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 参数与 constructor 参数混淆。试试tree&lt;int, std::less&lt;int&gt;&gt; my_bst(std::less&lt;int&gt;);

标签: c++ templates


【解决方案1】:

为了拯救你自己,以及其他只想要默认行为的人,在告诉编译器比较器的类型时额外的击键,你可以改为默认设置它,然后你只需要指定它,如果你想要不同的行为.

template<typename T, typename comparator = std::less<T>>
class tree
{
private:
    comparator compare;
public:
    explicit tree (comparator functor = comparator{});
};

将默认 comparator 类型为 std::less&lt;T&gt; 并让您像这样构造类

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

使用std::less&lt;int&gt; 创建tree


至于为什么可以这样做

std::vector<int> v;
std::sort(v.begin (), v.end (), std::less<>());

std::less 在 C++14 中专门用于std::less&lt;void&gt;,它提供了一个模板化的operator (),并将推断传递给它的类型。这意味着std::less&lt;&gt; 的对象可以比较任意两种类型,只要表达式

decltype(std::forward<T>(lhs) < std::forward<U>(rhs))

TU 都是operator () 的参数类型时有效。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-16
    • 1970-01-01
    • 2012-12-01
    • 1970-01-01
    • 2018-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多