问题
I have a class with a function
MyClass::doStuff(std::vector<MyCustomData*> toSort) { ...
in which I call
std::sort(toSort.begin(), toSort.end(), MyClass::SortByZ());
myClass::SortByZ() is a custom comparator. Now this works but I would like to achieve the following:
I have several classes, which should each have its own comparator functor to sort "MyCustomData". So e.g. Class1... should have
class Class1 {
struct SortData {
bool operator ()(MyCustomData *lhs, MyCustomData *rhs) {
return lhs->something1 > rhs->something1;
}
};
//...many more functions/vars
}
while Class2 has a different comparator functor for the same datatype eg
class Class2 {
struct SortData {
bool operator ()(MyCustomData *lhs, MyCustomData *rhs) {
return lhs->something2 > rhs->something2;
}
};
//...many more functions/vars
}
Now I would like to be able to call the function MyClass::doStuff(...) with either
doStuff(myData, Class1::SortData)
or
doStuff(myData, Class2::SortData)
and the function MyClass::doStuff(...) should use the respective Sort-Order.
I did not find out a way of doing this, is there one? I would like a simple solution (doesn't have to support templates or anything). I would be willing to use boost if I needed that, but a solution without boost would be preferred.
I hope I was able to describe what I want to achieve? Thanks for any help!
回答1:
You will have to make doStuff
a template:
template <typename Comparator>
void doStuff(std::vector<MyCustomData*> toSort, Comparator compare) {
// ...
std::sort(toSort.begin(), toSort.end(), compare);
// ...
}
Also, it might want to take the first argument by reference. As it is, it will sort a copy of the argument, discard that copy, and leave the caller's vector untouched; although perhaps that's what you want.
回答2:
Use a function template, in order to accept any kind of comparison function (or functor):
template <typename Comparator>
void doStuff(std::vector<MyCustomData> toSort, Comparator comparator)
{
...
std::sort(toSort.begin(), toSort.end(), comparator);
...
}
...
doStuff(myData, Class1::SortData());
doStuff(myData, Class2::SortData());
This is how standard algorithms provide genericity.
来源:https://stackoverflow.com/questions/10245728/pass-a-custom-comparator-through-a-function