在C++17中,你可以这样做:
您实际上不需要指定
但是等等...怎么做到的?!?
没有任何东西告诉
#include <iostream>
#include <algorithm>
#include <functional>
int main()
{
double values[5] = { 1.1, 2.2, 3.3, 4.4, 5.5 };
// Notice this:
std::sort(values, values+5, std::greater());
for(double v: values) std::cout << v << " ";
std::cout << "\n";
}
您实际上不需要指定
std::greater
的模板参数。
它将自动推断为double
。这非常好。但是等等...怎么做到的?!?
没有任何东西告诉
std::greater
模板参数应该是类型double
。
它没有采用任何构造函数参数之类的东西。
而且std::sort()
的声明明显是这样的:template<class RandomIt, class Compare>
void sort(RandomIt first, RandomIt last, Compare comp);
所以它里面没有任何内容表明它应该是双倍的。
那么怎么办?
std::greater<>
,它具有一个operator()
模板而不是固定类型。 - Quentin<>
) 可以省略。这实际上是 CTAD 的威力,而在“重复”的文章中没有提到。 - cpplearner()
到<void>
制定一个扣除指南,而不允许使用<>
。 (对于函数没有这样的区别,这可能影响了我的分析。) - Davis Herring