I've been playing about with functors in C++. In particular, I've got a vector of pairs I'd like to sort by the first element of the pair. I started off writing a completely specialised functor (i.e. something like "bool MyLessThan(MyPair &lhs, MyPair &rhs)"). Then, just because this sort of stuff is interesting, I wanted to try writing a generic "Apply F to the first elements of this pair" functor. I wrote the below, but g++ doesn't like it. I get:
error: type/value mismatch at argument 2 in template parameter list for 'template struct Pair1stFunc2' error: expected a type, got 'less'
#include <algorithm>
#include <functional>
#include <utility>
#include <vector>
template <class P, class F>
struct Pair1stFunc2
{
typename F::result_type operator()(P &lhs, P &rhs) const
{ return F(lhs.first, rhs.first); }
typename F::result_type operator()(const P &lhs, const P &rhs) const
{ return F(lhs.first, rhs.first); }
};
typedef std::pair<int,int> MyPair;
typedef std::vector<MyPair> MyPairList;
MyPairList pairs;
void foo(void)
{
std::sort(pairs.begin(),
pairs.end(),
Pair1stFunc2<MyPair, std::less>());
}
Can anyone shed any light on what I'm doing wrong here? I know this is as slightly artificial example, but I'd like to know what's going on, if only to improve my STL-fu.