2015-05-04 34 views
3

這在STL頭文件中定義:std ::更大<int>()期望0個參數(或1個參數),2個提供,爲什麼?

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。

+0

你試圖構造一個對象有兩個參數,但類沒有構造函數... –

回答

4

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&)

+0

這是一個類,但它有一個接收2個參數的'()'運算符。類名稱本身就是一個函子。 –

+0

另一個詞:爲什麼可以std :: sort()使用std :: greater ()作爲它的最後一個參數?我想創建一些這樣的功能。 –

+0

@RobinHsu所以創建一個類/結構體並重載'operator()'。 –

0

std::greater是一個類模板,而不是一個函數模板。表達式std::greater<int>(3,2)嘗試調用構造函數std::greater<int>,並取兩個整數。

您需要創建它的一個實例,然後在其上使用operator()

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