5.2.23 · D3C++ Programming

Worked examples — std - function and std - bind

2,056 words9 min readBack to topic

This page is a drill. We enumerate every shape of situation std::function and std::bind can put in front of you, then work one example per shape. If you have not met the wrapper idea yet, read the parent std::function and std::bind first — this page assumes you know that std::function<R(Args...)> stores any callable matching the signature, and that std::bind pre-fills arguments.

Before we start, one word we will lean on constantly: arity. The arity of a callable is simply how many arguments it takes. sub(a,b) has arity 2. When we bind, we usually lower the arity — we hand over fewer arguments because some are remembered in advance. Keep that picture in mind:

Figure — std - function and std - bind

The scenario matrix

Every case below is a cell. The worked examples are labelled with the cell they hit, and together they cover the whole grid.

Cell What it stresses Callable kind bind action
C1 Store & swap different callables in one variable free fn / lambda / functor none
C2 Container of callbacks (heterogeneous types) lambdas none
C3 Fix one argument (arity 2 → 1) free fn fix + _1
C4 Reorder arguments (no arity change) free fn _2, _1
C5 Drop an argument entirely (arity down, unused call arg) free fn fix only
C6 Bind a member function (hidden this) member fn object + _1
C7 Reference semantics — copy vs std::ref lambda over state fix by ref
C8 Degenerate: empty std::function called none none
C9 Limiting: arity 0, and nesting bind-in-bind free fn _1 reuse
C10 Exam twist — evaluation order of side effects free fn _1, _1

C1 — One variable, three creatures


C2 — A container of callbacks


C3 — Fix one argument (arity 2 → 1)


C4 — Reorder arguments (arity unchanged)


C5 — Drop an argument entirely


C6 — Bind a member function (the hidden this)


C7 — Copy vs std::ref (the reference trap)


C8 — Degenerate: calling an empty std::function


C9 — Limiting cases: arity 0, and nesting


C10 — Exam twist: side effects and placeholder reuse


Recall Cover the matrix from memory

Which cell tests dropping an argument? ::: C5 — all slots fixed, extra call args ignored. Which cell throws? ::: C8 — calling an empty std::function throws std::bad_function_call. How do you keep a real reference through std::bind? ::: Wrap the arg in std::ref (C7); bind copies by default. Can _1 appear twice in one bind expression? ::: Yes — it's a substitution rule, so the same call arg feeds every _1 slot (C9b).

See also: Lambda Expressions, Function Pointers, Functors and operator(), Templates and Type Erasure, Callbacks and Event Systems.