c++ - 模板函数参数的含义是什么?

标签 c++ algorithm templates sorting c++11

我遇到了以下模板函数,

template<typename C, typename F = less<typename C::value_type>> void Sort(C& c, F f = F()){
    sort(C.begin(),c.end(),f);
}

现在,我在 less 中查找,它表明,

Binary function object class whose call returns whether the its first argument compares less than the second (as returned by operator <).

在上面提到的函数中less有什么用?它只有一个参数。

谢谢。

最佳答案

没有。 less没有 1 个参数。它有 1 个模板参数。这与 1 个参数不同。 它也是一个类而不是一个函数。更准确地说,它是一个 functor - 一个重载的类 ()运算符,因此它可以用作函数。

考虑这样的实现

template<class T>
struct less 
{   
    bool operator()(const T& left, const T& right) const
    {
        return (left < right);
    }
};

less<int>可以称为

less<int> f;
f(a,b);

其中 a 和 b 是 int

所以有一个模板参数(T == int),但是有 2 个参数(int left & int right)。

关于c++ - 模板函数参数的含义是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19651743/

相关文章:

algorithm - 在分析算法的时间复杂度时,为什么要舍弃度数最大项的常​​量

javascript - 'into' 警告从多个 this.render() 抛入 Ember.js

c++ - 使用 std::remove_if() 时没有可行的重载 '='

c++ - 具有 pqxx 结果的模板函数

c++ - 使用 constexpr 和 CryptoPP 的编译时散列

c++ - 使用 minGW 构建 crypto562

c++ - 在 C 代码中为 Matlab/LabView 接口(interface)创建 DLL 包装器

algorithm - 元素数组的多个查询更新

c++ - 堆栈实现

c# - 用一对或多对字符之间的点确定单词排列的算法