Legacy C++ › 6. The Standard Template Library
Function Objects and Binders
Functors, predicates, bind1st/bind2nd and mem_fun.
intermediate #functors#function-objects#predicates#bind1st#bind2nd#mem_fun#ptr_fun
Explanation
A function object (functor) is any object that can be called like a function, because its class overloads operator(). Unlike a plain function pointer, a functor can carry state and the compiler can inline its call, so STL algorithms like std::sort often run faster with a functor than a function pointer.
- A predicate returns
bool(unary or binary) and drivesfind_if,sort,remove_if. <functional>provides ready-made functors:std::plus,std::minus,std::less,std::greater,std::equal_to,std::logical_not, and more.- Binders and adaptors (C++98):
bind1st/bind2ndfix one argument of a binary functor;not1/not2negate;ptr_funwraps a function;mem_fun/mem_fun_refcall a member function. They were deprecated in C++11 and removed in C++17, replaced bystd::bindand lambdas.
Example
#include <algorithm>
#include <functional>
#include <iostream>
#include <vector>
class GreaterThan { // a stateful predicate
int limit_;
public:
explicit GreaterThan(int l) : limit_(l) {}
bool operator()(int x) const { return x > limit_; }
};
class Accumulator { // keeps a running total
int total_;
public:
Accumulator() : total_(0) {}
void operator()(int x) { total_ += x; }
int total() const { return total_; }
};
int main() {
std::vector<int> v;
for (int i = 1; i <= 10; ++i) v.push_back(i);
std::cout << std::count_if(v.begin(), v.end(), GreaterThan(7)) << "\n"; // 3
// for_each returns the functor, so we can read its state afterwards
Accumulator acc = std::for_each(v.begin(), v.end(), Accumulator());
std::cout << acc.total() << "\n"; // 55
std::sort(v.begin(), v.end(), std::greater<int>()); // descending
std::cout << v.front() << "\n";
// C++98 binder: count elements greater than 5 (5 < x)
std::cout << std::count_if(v.begin(), v.end(), std::bind2nd(std::greater<int>(), 5)) << "\n";
return 0;
}
std::bind2ndcompiles in C++98 through C++14 (deprecated since C++11), and is removed in C++17. In new code write[](int x){ return x > 5; }.
Common pitfalls
operator()should usually beconstfor predicates; algorithms may copy the functor.- Algorithms copy functors, so state kept in the original is not updated. Use the returned functor (
for_each) or hold a pointer/reference. - Predicates must be side-effect free and consistent, especially for
sort. - Binder error messages are famously unreadable, and
bind2ndfails with reference parameters. - Passing a member function to an algorithm needs
mem_fun; this was error-prone.
Legacy vs modern
C++11 replaces all of this with lambdas ([limit](int x){ return x > limit; }), std::bind, std::function, std::mem_fn. See Lambda Expressions.
Exercises
1. Write a functor Between(lo, hi) for std::find_if.
struct Between {
int lo, hi;
Between(int l, int h) : lo(l), hi(h) {}
bool operator()(int x) const { return lo <= x && x <= hi; }
};