【问题标题】:Using default predicate for sort with templates. C++使用模板排序的默认谓词。 C++
【发布时间】:2019-11-27 20:00:53
【问题描述】:

我正在尝试定义如下所示的类模板

template <typename T> class test{
       std::list<T> container;
       public:
       template <typename type, typename PRED = std::greater<int>>
        void push(type e, PRED comp = std::greater<int>) {
            container.push_back(e);
            container.sort(comp);
        }

};

从 main 我希望能够告诉 sort 应该如何进行排序。但如果没有指定,我也想排序使用 std::greater 。上面的代码告诉我 std::greater 是非法的。

【问题讨论】:

  • std::greater 位于 functional 标头中。你还记得#include &lt;functional&gt; 吗?
  • std::greater&lt;int&gt;class 不是默认参数所需的实例。由于 PRED 类型已经是正确的类型,您可以使用 PRED() 作为默认参数的对象。
  • 应该是PRED comp = std::greater&lt;int&gt;{}
  • 对于未来的问题,请阅读how to ask good questionsthis question checklist,并尝试创建一个合适的minimal reproducible example 向我们展示。并包括您从构建中获得的所有错误,完整复制粘贴为文本。

标签: c++


【解决方案1】:

您可能想要这样做:

template <typename type, typename PRED = std::greater<T>>
void push(type e, PRED comp = PRED()) {
    // ...
}

使用std::greater&lt;T&gt; 作为默认模板参数,这样即使T 不是int 也能正常工作。

使用PRED() 作为comp 参数的默认值,这样即使用户指定了一些其他可默认构造的谓词类型(如std::less&lt;T&gt;),它也能正常工作。

【讨论】:

  • 这正是我想要的。以为我从 开始让自己轻松。但我想我错过了关键的 PRED comp = PRED()。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-29
  • 2018-07-15
相关资源
最近更新 更多