Skip to content
Tutorials Center
My learning

Topics

Lesson 106 of 171 ยท The Standard Library (STL)

Function Objects and std::function

Learn C++ function objects - writing functors, std::less and std::greater, transparent comparators, std::function vs templates, std::invoke, bind_front and not_fn.

A function object is anything you can call with (): a plain function, a function pointer, a lambda, or an object of a class that defines operator(). That last kind is traditionally called a functor. The STL is built around function objects. std::sort takes a comparison, std::map stores one as its ordering, std::priority_queue uses one to decide which element is on top, and std::unordered_map uses a hasher and an equality function.

In Lambda Expressions you learned the most convenient way to create function objects. This lesson looks at the bigger picture: writing your own functor classes and when they beat a lambda, the ready-made function objects in <functional> (std::less, std::greater, std::plus and friends), transparent comparators, the type-erasing wrapper std::function and its C++23 sibling std::move_only_function, the uniform calling helper std::invoke, and the adapters std::bind_front, std::bind_back, std::not_fn and std::ref. You'll finish with a clear rule for choosing between templates and std::function.

Writing a functor

A functor is an ordinary class with an operator(). Because it's a class, it can hold data members (state), have a constructor that checks its arguments, provide several overloads of operator(), and have a name that you can reuse across many files.

C++ Functor classes with state

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Two details are worth noticing. InRange::operator() is const: predicates passed to algorithms shouldn't change state, and the algorithm is allowed to copy them. And std::ranges::for_each returns the function object it used, which is the reliable way to get state back from a stateful functor; the original Stats{} you passed was a temporary copy.

A lambda is shorter for one-off rules. Reach for a named functor when the same rule is used in many places, needs validation in its constructor, or needs several overloads of operator() (for example a comparator that accepts both a Person and a std::string).

Standard function objects in <functional>

The header <functional> provides class templates for every built-in operator, so you don't have to write tiny lambdas for them:

Arithmetic Comparison Logical and bitwise
std::plus, std::minus std::equal_to, std::not_equal_to std::logical_and, std::logical_or
std::multiplies, std::divides std::less, std::less_equal std::logical_not
std::modulus, std::negate std::greater, std::greater_equal std::bit_and, std::bit_or, std::bit_xor, std::bit_not

You can write them with a type, std::greater<int>{}, or without one, std::greater<>{}. The empty-bracket form (C++14) is a transparent function object: its operator() is a template that accepts any two types that can be compared, and it never converts the arguments first. Prefer std::greater<> and std::less<> in new code.

C++ std::greater, std::plus and transparent comparators

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The last part shows why transparency matters. With the default std::map<std::string, int>, which uses std::less<std::string>, stock.find(wanted) wouldn't even compile for a std::string_view, and find("kiwi") would build a temporary std::string for every lookup. With std::less<>, the map compares the string_view directly against its keys. This is called heterogeneous lookup. Unordered containers support it too (C++20), but they need both a transparent hasher and a transparent equality.

std::function: one type for any callable

Every lambda has its own type, and so does every functor class. That's great for templates, but sometimes you need one type that can hold any of them: a member variable that stores a callback, a std::vector of event handlers, or a map from command names to actions. That's std::function<R(Args...)>.

std::function uses type erasure: it hides the concrete type of whatever you store behind a uniform call interface. You pay for this flexibility in three ways:

  • An indirect call each time it's invoked, which the optimizer usually can't inline.
  • A possible heap allocation when the stored callable is larger than the small internal buffer (implementations store small lambdas inline).
  • Copyability is required. The stored callable must be copyable, so a lambda that owns a std::unique_ptr can't go in. C++23's std::move_only_function lifts that restriction.

An empty std::function converts to false, and calling it throws std::bad_function_call.

C++ An event dispatcher with std::function

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

If a key were missing, ops["name"] on a std::map would insert a default-constructed, empty std::function, and calling it would throw. In real code, look commands up with find or contains first (see std::map).

Templates or std::function?

When you write a function that accepts a callable, you have two main choices:

C++
// 1. A template: each callable type gets its own instantiation.
void repeat(int times, std::invocable<int> auto action) {
    for (int i = 0; i < times; ++i) {
        action(i);
    }
}

// 2. std::function: one compiled function for every callable.
void repeat_erased(int times, const std::function<void(int)>& action) {
    for (int i = 0; i < times; ++i) {
        action(i);
    }
}
Template parameter std::function
Speed the call can be inlined; zero overhead indirect call, maybe an allocation
Code location must be in a header can live in a .cpp file
Storing in members / containers awkward (type is part of the class) easy
Binary size one copy per callable type one copy total
Error messages constrain with std::invocable for clarity signature mismatch reported at the call site

The rule of thumb: take a template when you call the function object right away; use std::function when you need to store it. That's exactly how the STL is designed: algorithms take templates, while things like callbacks in a GUI framework store std::function. C++26 adds std::function_ref, a lightweight non-owning reference to a callable for parameters that are called immediately but shouldn't be templates; it isn't available in our compiler yet.

std::invoke: one way to call everything

Calling a member function through a pointer to member uses awkward syntax: (obj.*pmf)(args) or (ptr->*pmf)(args). Generic code that accepts "any callable" would need a different spelling for functions, functors, member function pointers and data member pointers. std::invoke(f, args...) from <functional> handles all of them:

  • std::invoke(f, a, b) calls f(a, b) for functions, lambdas and functors.
  • std::invoke(&Class::method, obj, a) calls obj.method(a); obj may be an object, a reference, a pointer or a smart pointer.
  • std::invoke(&Class::member, obj) returns obj.member.

This is exactly how the projections of the std::ranges algorithms work, which is why you can pass a pointer to a data member to sort by a field.

C++ std::invoke, member pointers and projections

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

In std::ranges::sort(team, {}, &Employee::age), the {} means "the default comparator" (std::ranges::less), and &Employee::age is the projection applied to each element before comparing. Ranges and Views uses projections heavily. C++23 also adds std::invoke_r<R>(...), which converts the result to R.

Adapting callables: bind_front, bind_back, not_fn and ref

Sometimes you have a function with the wrong shape: it takes three arguments, but the algorithm will call it with one. Adapters create a new function object from an existing one:

  • std::bind_front(f, a, b) (C++20) fixes the first arguments: calling the result with x calls f(a, b, x).
  • std::bind_back(f, z) (C++23) fixes the last arguments: calling it with x calls f(x, z).
  • std::not_fn(pred) (C++17) negates a predicate.
  • std::ref(x) and std::cref(x) wrap a reference in a copyable std::reference_wrapper, so adapters, std::thread and other copying APIs refer to your object instead of copying it.

The older std::bind with placeholders (std::placeholders::_1) still exists, but it's hard to read and has surprising rules. A lambda or std::bind_front is almost always clearer.

C++ bind_front, bind_back, not_fn and std::ref

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Read std::bind_front(price_with_tax, 19.0, 5.0) as "a function like price_with_tax with its first two arguments already filled in". If you leave out std::ref(counter), the code still compiles, but count_long increments a copy stored inside the adapter and counter stays 0. That silent copy is the single most common mistake with adapters and with std::thread.

Choosing the right callable

  • Inline, one-off rule: a lambda.
  • Standard operator: std::less<>, std::greater<>, std::plus<> and friends. They're shorter than a lambda and transparent.
  • Rule reused across the codebase, or with validation or several overloads: a named functor class.
  • Calling a member through a pointer, or writing generic "call anything" code: std::invoke (and projections in std::ranges).
  • Fixing some arguments: std::bind_front or a lambda; avoid std::bind.
  • Storing callables of different types: std::function, or std::move_only_function for move-only ones.
  • Accepting a callable you call right away: a constrained template parameter, std::invocable<Args...> auto f.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. std::set<int, std::greater<>> s{3, 1, 2}; In what order does a range-for visit the elements?

    The comparator defines the set's order. std::greater puts larger elements first, so the set is ordered 3, 2, 1.
  2. 2. What happens when you call a default-constructed std::function<void()>?

    An empty std::function converts to false, and calling it throws std::bad_function_call.
  3. 3. int n = 0; auto f = std::bind_front([](int& x) { ++x; }, n); f(); f(); What is n afterwards?

    Adapters store copies of their bound arguments, so the lambda increments the adapter's own copy. Pass std::ref(n) to bind the original.
  4. 4. Why can std::map<std::string, int, std::less<>> find a key from a std::string_view directly, while std::map<std::string, int> cannot?

    Transparent comparators enable the template overloads of find, count, contains and lower_bound that accept any comparable type.
  5. 5. You are writing a function that calls a passed-in callable once, immediately, in a hot loop. What is the best parameter type?

    A template sees the exact callable type, so the call can be inlined. std::function and function pointers add an indirect call.

Summary

  • A function object is anything callable with (); a functor is a class with operator() that can hold state, validate it and offer overloads.
  • <functional> provides std::plus, std::less, std::greater and the other operator objects; the empty-bracket forms like std::less<> are transparent and enable heterogeneous lookup.
  • std::function<R(Args...)> stores any copyable callable with a matching signature at the cost of an indirect call and possibly an allocation; empty ones throw std::bad_function_call. std::move_only_function (C++23) stores move-only callables.
  • Take templates for callables you call immediately, std::function for callables you store.
  • std::invoke calls functions, functors and member pointers uniformly; ranges projections are built on it.
  • std::bind_front, std::bind_back and std::not_fn adapt callables; wrap arguments in std::ref when the adapter must refer to your variable instead of copying it.

Next: Algorithms: Searching, Sorting and Counting, where you'll put comparators and predicates to work with sort, find_if, lower_bound and more.