这是在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:QtToolsmingw482_32i686-w64-mingw32includec++bitsstl_function.h:222: std::greater<int>::greater()
struct greater : public binary_function<_Tp, _Tp, bool>
^
C:QtToolsmingw482_32i686-w64-mingw32includec++bitsstl_function.h:222: note: candidate expects 0 arguments, 2 provided
C:QtToolsmingw482_32i686-w64-mingw32includec++bitsstl_function.h:222: std::greater<int>::greater(const std::greater<int>&)
C:QtToolsmingw482_32i686-w64-mingw32includec++bitsstl_function.h:222: note: candidate expects 1 argument, 2 provided
怎么了?当然,编译器是mingw(GCC)。
这是我的代码的简化版本。实际上,我正在使用std ::更复杂的排序算法。
std::greater<...>
是类,而不是函数。该类已超载operator()
,但是您需要一个类的对象才能调用该操作员。因此,您应该创建一个类的实例,然后称其为:
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
是类模板,而不是函数模板。表达式std::greater<int>(3,2)
试图调用std::greater<int>
的构造函数,取两个ints。
您需要创建一个实例,然后在其上使用operator()
:
cout << (std::greater<int>{}(3, 2)? "TRUE":"FALSE") << endl;