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

This is defined in the STL header file:

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

      

I wrote one simple simple code like below:

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

      

It doesn't compile. Error message:

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

      

What happened? The compiler is of course minGW (GCC).

This is a simplified version of my codes. In fact, I use std :: more in my complex sorting algorithm.

+3


source to share


2 answers


std::greater<...>

is a class, not a function. This class has overloaded operator()

, but you need a class object to invoke this operator. Therefore, you have to create an instance of the class and then call it:

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

      



Here, the first pair of brackets ( #1

) instantiates std::greater<int>

and #2

calls std::greater<int>::operator()(const int&, const int&)

.

+4


source


std::greater

is a class template, not a function template. The expression std::greater<int>(3,2)

tries to call a constructor std::greater<int>

with two ints.

You need to instantiate and then use operator()

on it:



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

      

0


source







All Articles