本文介绍了为什么当类在main()内时,std :: sort谓词失败?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个非常简化的再现,说明类谓词 delcared外 main()工作,代码以类InlinePredicate 内联显示,编译器不能匹配 std :: sort 。奇怪的是,你可以传递任何作为第三个参数 std :: sort (比如说,整数7),你会得到当它不支持运算符()排序期望时的编译错误。但是当我通过 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<秒;
}
};

int
main()
{
vector< pair< string,int& >一个;

谓词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<秒;
}
} pred2;
sort(a.begin(),a.end(),pred2);

return 0;
}



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

p>

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


This is a much simplified repro which illustrates how class Predicate delcared outside main() works but when the exact code appears inline as class InlinePredicate the compiler can't match std::sort. The strange thing is that you can pass anything as the third argument to std::sort (say, integer 7) and you'll just get a compile error when it does not support the operator () that sort expects. But when I pass pred2 below it doesn't match at all:

#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;
}
解决方案

In C++03, local classes have no linkage and consequently cannot be used as template arguments (§14.3.1/2).

In C++0x, this limitation has been removed and your code would compile as-is.

这篇关于为什么当类在main()内时,std :: sort谓词失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 16:55