我在工作,在一个函数中编写比较器(稍后移动,当我决定哪里最好时),并注意到了这个特殊性。我想了一会儿,意识到我不明白为什么如果我使用内部比较器,代码将无法编译,但外部比较器很好。
有什么解释吗?
快速测试工具:
#include <iostream>
#include <vector>
#include <algorithm>
class CompareMe
{
public:
CompareMe(int in) : toCompare(in){}
int toCompare;
};
class Comparators
{
public:
bool operator()(CompareMe * first, CompareMe * second)
{
return first->toCompare < second->toCompare;
}
};
class ComparatorsOuter : public Comparators{};
int main()
{
class ComparatorsInner : public Comparators{};
std::vector<CompareMe *> compares;
compares.push_back(new CompareMe(0));
compares.push_back(new CompareMe(1234));
compares.push_back(new CompareMe(163));
compares.push_back(new CompareMe(6));
compares.push_back(new CompareMe(12));
//This works, and properly sorts the array
ComparatorsOuter comparator;
std::sort(compares.begin(), compares.end(), comparator);
//Uncomment out the sort below and it will not compile.
ComparatorsInner comparatorInner;
//std::sort(compares.begin(), compares.end(), comparatorInner);
std::vector<CompareMe *>::iterator it;
for(it = compares.begin(); it != compares.end(); ++it)
{
std::cout << (*it)->toCompare << std::endl;
}
}
错误:没有匹配的函数调用“
sort(__gnu_cxx::__normal_iterator<CompareMe**, std::vector<CompareMe*, std::allocator<CompareMe*> > >, __gnu_cxx::__normal_iterator<CompareMe**, std::vector<CompareMe*, std::allocator<CompareMe*> > >, main()::ComparitorInner&)
”