这是一个简单的示例,它说明了在外部声明
class Predicate
时的工作方式,但当完全相同的代码作为class InlinePredicate
内联出现时,编译器无法匹配std::sort
。奇怪的是,您可以将std::sort
的第三个参数传递为任何(例如整数7),并且只有当不支持sort
所需的operator()
时才会出现编译错误。但当我传递下面的pred2
时,它根本无法匹配:#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: 在函数 ‘int main()’ 中:
repro.cc:30: 错误:没有找到与‘sort(__gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int> > >, __gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int> > >, main()::InlinePredicate&)’相匹配的函数
const bool operator()(const pair<string,int>& a, const pair<string,int>& b) **const**
。 - Martin York