Functors & Predicates
Why a functor instead of a plain function?
A stateful counting functor and a configurable multiplier
#include <algorithm>
#include <iostream>
#include <vector>
// A functor that remembers how many times it has been invoked.
class CallCounter {
public:
void operator()(int value) {
++calls;
std::cout << "Saw: " << value << "\n";
}
int callCount() const { return calls; }
private:
int calls = 0;
};
// A functor configured once at construction, then reused.
class Multiplier {
public:
explicit Multiplier(int factor) : factor(factor) {}
int operator()(int value) const { return value * factor; }
private:
int factor;
};
int main() {
std::vector<int> nums = {1, 2, 3, 4};
CallCounter counter;
// std::for_each returns the (possibly mutated) functor by value.
counter = std::for_each(nums.begin(), nums.end(), counter);
std::cout << "Total calls: " << counter.callCount() << "\n";
Multiplier triple(3);
std::vector<int> tripled(nums.size());
std::transform(nums.begin(), nums.end(), tripled.begin(), triple);
for (int n : tripled) std::cout << n << " ";
std::cout << "\n";
return 0;
}Predicates
A predicate functor used with sort and count_if
#include <algorithm>
#include <iostream>
#include <vector>
struct IsEven {
bool operator()(int n) const { return n % 2 == 0; }
};
int main() {
std::vector<int> nums = {5, 3, 8, 1, 9, 4};
int evenCount = std::count_if(nums.begin(), nums.end(), IsEven());
std::cout << "Even numbers: " << evenCount << "\n";
// Sort so that even numbers come before odd numbers.
std::sort(nums.begin(), nums.end(),
[](int a, int b) { return IsEven()(a) && !IsEven()(b); });
for (int n : nums) std::cout << n << " ";
std::cout << "\n";
return 0;
}Aspect | Functor | Lambda |
|---|---|---|
Reusability | Named class, reusable anywhere | Best for one-off, local use |
State | Member variables, explicit and named | Captures by value/reference |
Readability at call site | Just a type name | Full logic visible inline |
Typical use today | Reusable, stateful, library-facing callables | Quick inline callbacks for a single algorithm call |
A functor is a class instance that overloads operator(), making it callable like a function.
Unlike a plain function pointer, a functor can carry state and is often easier to inline.
A predicate is any callable returning bool, used to drive conditional algorithms.
Modern code favors lambdas for one-off callables; functors remain useful for reusable, stateful ones.