There is my program that illustrates predicate template that could be used as sorting predicate for STL containers instantiation:
#include <iostream>
#include <set>
#include <iterator>
#include <algorithm>
#include <functional>
#include <string>
using namespace std;
template<typename T, template <typename> class comp = std::less> struct ComparePtr: public binary_function<T const *, T const *, bool> {
bool operator()(T const *lhs, T const *rhs) const {
comp<T> cmp;
return (cmp(*lhs, *rhs));
}
};
int wmain() {
string sa[] = {"Programmer", "Tester", "Manager", "Customer"};
set<string *, ComparePtr<string>> ssp;
for (int i(0) ; i < sizeof sa/sizeof sa[0] ; ++i)
ssp.insert(sa + i);
for_each(ssp.begin(), ssp.end(), [](string *s){ cout << s->c_str() << endl; });
return 0;
}
Please, focus on predicate: is it written correctly?
Is it good to instantiate comp? Is there a way that allows not to instantiate comp predicate?
Why use a template template at all and not just add a simple wrapper around general binary comparators?
Boost Pointer Containers could also make this a lot easier.
Ildjarn showed how to implement your functor correctly:
This way it isn’t necessary to specify the type of the arguments anymore.
Edit: There used to be
std::forwardand rvalue references in my code, which made absolutely no sense.