First of all, it should be noted that the standard provides very few guarantees regarding how many copies will be made for function objects. If you need to use full-featured functions, you should use referential semantics (have the state that the functor points to, rather than being held inside).
Thus, the first option is to refactor the functor or package it:
struct Wrapper { Comparator *cmp; Wrapper(Comparator *cmp) : cmp(cmp) {} bool operator()(T const & lhs, T const & rhs) const { return (*cmp)(lhs,rhs); } }; Comparator cmp(...); Wrapper w(&cmp); sort(v.begin(), v.end(), w);
This is actually the same thing you would get if you use std::ref (C ++ 11) directly:
Comparator cmp(...); sort(v.begin(), v.end(), std::ref(cmp));
David Rodríguez - dribeas
source share