std::greater<int>() 预期 0 个参数(或 1 个参数),提供 2 个,为什么?

std::greater<int>() expected 0 arguments (or 1 arguments), 2 provided, why?

这是在STL头文件中定义的:

template<typename _Tp>
    struct greater : public binary_function<_Tp, _Tp, bool>
    {
      bool
      operator()(const _Tp& __x, const _Tp& __y) const
      { return __x > __y; }
    };

我只写了一行简单的代码如下:

cout << (std::greater<int>(3, 2)? "TRUE":"FALSE") << endl;

它不编译。错误信息是:

C:\Qt\Tools\mingw482_32\i686-w64-mingw32\include\c++\bits\stl_function.h:222: std::greater<int>::greater()
     struct greater : public binary_function<_Tp, _Tp, bool>
            ^
C:\Qt\Tools\mingw482_32\i686-w64-mingw32\include\c++\bits\stl_function.h:222: note:   candidate expects 0 arguments, 2 provided
C:\Qt\Tools\mingw482_32\i686-w64-mingw32\include\c++\bits\stl_function.h:222: std::greater<int>::greater(const std::greater<int>&)
C:\Qt\Tools\mingw482_32\i686-w64-mingw32\include\c++\bits\stl_function.h:222: note:   candidate expects 1 argument, 2 provided

怎么了? 编译器当然是 minGW (GCC)。

这是我的代码的简化版本。事实上,我在复杂的排序算法中使用了std::greater。

std::greater<...> 是一个 class,不是函数。此 class 已重载 operator(),但您需要 class 的对象来调用该运算符。所以你应该创建一个 class 的实例,然后调用它:

cout << (std::greater<int>()(3, 2)? "TRUE":"FALSE") << endl;
//                        #1  #2

这里第一对括号(#1)创建了一个std::greater<int>的实例,#2调用了std::greater<int>::operator()(const int&, const int&).

std::greater 是 class 模板,不是函数模板。表达式 std::greater<int>(3,2) 试图调用带有两个整数的 std::greater<int> 的构造函数。

您需要创建它的实例,然后在其上使用 operator()

cout << (std::greater<int>{}(3, 2)? "TRUE":"FALSE") << endl;