c++ - std::less<int> 的正确参数类型是什么?

标签 c++ templates

我正在制作一个类——一个 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 都有效的情况下有效和 Uoperator () 的参数类型.

关于c++ - std::less<int> 的正确参数类型是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52598616/

相关文章:

c++ - Usrp 全双工操作

c++ - 需要帮助使用 C++ 加载简单的文本数据

c++ - 我可以在字符串中包含 vector 吗?

c++ - 使用 std::array<Type, N> 的实例作为模板参数

c++ - 编译时数组常量

c++ - 从派生类调用父类的模板函数

c++ - CallWindowProc()生成错误5(访问被拒绝)

c++ - c++ 模板元编程是函数式编程的一种形式吗

php - 解析电子邮件或 html 模板的最佳方法是什么?

c++ - 在 C++ 中访问参数包的内部变量