C++17 template argument deduction mystery

War*_*arp 5 c++ templates c++17

In C++17 you can do this:

#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";
}
Run Code Online (Sandbox Code Playgroud)

You don't actually need to specify the template parameter of std::greater. It will be automatically deduced as double. That's really nice.

But wait... How?!?

There's nothing telling std::greater that the template parameter should be of type double. It's not taking any constructor parameters or anything. And the declaration of std::sort() is ostensibly like this:

template<class RandomIt, class Compare>
void sort(RandomIt first, RandomIt last, Compare comp);
Run Code Online (Sandbox Code Playgroud)

so there's nothing there telling it that it should be double either.

So how?

Mar*_*low 5

的定义有两种std::greater。一个需要在类型上使用模板参数,而另一个则不需要。

您正在使用第二个。

这是什么std::greater样子(离开过类似修饰constexpr,并noexcept与不同的返回类型):

template <typename T = void>
struct greater
{
    bool operator () (const T& x, const T& y) { return x > y; }
};

template <>
struct greater<void>
{
    template <typename T1, typename T2>
    bool operator () (const T1& x, const T2& y) { return x > y; }
    typedef void is_transparent;
};
Run Code Online (Sandbox Code Playgroud)