I was at work, writing the Comparators in a function (to move later, when I decided where was best), and noticed this peculiarity. I thought about it for a while, and realized I do not understand exactly why the code will not compile if I use the inner comparators, but the outer one is fine.
Any explanations?
Quick Test harness:
#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;
}
}
error: no matching function for call to '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&)
'
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…