這是一個非常簡單的repro,它說明class Predicate
如何在main()
以外工作,但是當確切代碼內嵌爲class InlinePredicate
時,編譯器不能匹配std::sort
。奇怪的是,你可以通過任何東西作爲std::sort
(比如說整數7)的第三個參數,當它不支持sort
期望的operator()
時,你會得到一個編譯錯誤。但是,當我通過pred2
下面不匹配都:爲什麼這個std :: sort謂詞失敗,當類在main()內?
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
class Predicate {
public:
bool operator() (const pair<string,int>& a, const pair<string,int>& b)
{
return a.second < b.second;
}
};
int
main()
{
vector<pair<string, int> > a;
Predicate pred;
sort(a.begin(), a.end(), pred);
class InlinePredicate {
public:
bool operator() (const pair<string,int>& a, const pair<string,int>& b)
{
return a.second < b.second;
}
} pred2;
sort(a.begin(), a.end(), pred2);
return 0;
}
repro.cc: In function ‘int main()’:
repro.cc:30: error: no matching function for call to ‘sort(__gnu_cxx::__normal_iterator, std::allocator >, int>*, std::vector, std::allocator >, int>, std::allocator, std::allocator >, int> > > >, __gnu_cxx::__normal_iterator, std::allocator >, int>*, std::vector, std::allocator >, int>, std::allocator, std::allocator >, int> > > >, main()::InlinePredicate&)’
補充說明:您的運營商可能應該是const'布爾運算符()(常量對&A,常量對&B)** **常量' –