这是一个非常简化的class Predicate
repro ,它说明了外部的delcared 是如何main()
工作的,但是当精确的代码出现在内联时,因为class InlinePredicate
编译器无法匹配std::sort
.奇怪的是,你可以通过任何东西作为第三个参数std::sort
(比如,整数7),你会只得到,当它不支持编译错误operator ()
是sort
期待.但是当我从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;
}
Run Code Online (Sandbox Code Playgroud)
repro.cc:在函数'int main()'中:
repro.cc:30:错误:没有匹配函数来调用'sort(__ gnu_cxx :: __ normal_iterator,std :: allocator>,int>*,std :: vector,std :: allocator>,int>,std :: allocator ,std :: allocator>,int >>>>,__ nuu_cxx :: __ normal_iterator,std :: allocator>,int>*,std :: vector,std :: allocator>,int>,std :: allocator,std :: allocator>,int >>>>,main():: InlinePredicate&)'
在C++ 0x之前的C++版本中,在函数内声明的类不能出现在模板参数中.您的调用sort
使用模板参数设置为隐式实例化InlinePredicate
,这是非法的.
您可能需要考虑使用C++ 0x(使用GCC,传递--std=c++0x
;在C++ 0x中,此代码将按原样运行,或者您可以使用匿名函数),或boost::lambda
.有boost::lambda
,它看起来像这样:
using namespace boost::lambda;
sort(a.begin(), a.end(), _1 < _2);
Run Code Online (Sandbox Code Playgroud)