当类在main()中时,为什么这个std :: sort谓词会失败?

Ben*_*son 8 c++ templates stl

这是一个非常简化的class Predicaterepro ,它说明了外部的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&)'

ild*_*arn 9

在C++ 03中,本地类没有链接,因此不能用作模板参数(§14.3.1/ 2).

在C++ 0x中,此限制已被删除,您的代码将按原样编译.


bdo*_*lan 5

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