5.2.23C++ Programming

std - function and std - bind

2,002 words9 min readdifficulty · medium

WHY does this exist?


std::function


std::bind

HOW placeholders map arguments

When you later call the bound object with arguments (c1,c2,)(c_1, c_2, \dots):

  • A fixed value in the bind expression is used as-is.
  • A placeholder _n is replaced by the n-th call argument cnc_n.
Figure — std - function and std - bind

bind vs lambda (the modern truth)


Common mistakes


Recall Feynman: explain to a 12-year-old

Imagine a TV remote (std::function). It has buttons of a fixed shape (the signature). You don't care if the remote talks to a Sony or a Samsung TV — pressing the button just works. std::function is a remote that can be pointed at any "TV" (function, lambda, etc.) that understands the same buttons. Now std::bind is like pre-setting a button: you have a volume button that takes "which TV" and "how loud". You stick a label "always the living-room TV" on it, so now the button only asks "how loud?". You've remembered part of the answer in advance.


Flashcards

What does std::function<R(Args...)> store?
Any callable (free fn, lambda, functor, member fn) whose call matches signature R(Args...), via type erasure.
Why can't you put two different lambdas in the same variable directly?
Each lambda has its own unique unnamed type; std::function unifies them under one signature-based type.
What happens when you call an empty std::function?
It throws std::bad_function_call.
What does std::bind do conceptually?
Partial application: fixes some arguments now, leaves placeholders for the rest, producing a new callable.
What does the placeholder _2 mean?
The second argument supplied when the bound object is later called (not the 2nd item in the bind list).
How do you pass an argument by reference to std::bind?
Wrap it in std::ref(x) (or std::cref(x)); bind copies by value otherwise.
How do you bind a member function addBase of object c?
std::bind(&Counter::addBase, &c, _1) — the object/pointer is the first bound argument (the implicit this).
Why is std::function not zero-cost?
It may heap-allocate and uses an indirect/virtual call, so it can't be inlined like a direct call.
Modern preference: bind or lambda?
Lambda — clearer and usually faster; bind mostly survives in legacy code.
Give the bind expression that swaps args of sub(a,b).
std::bind(sub, _2, _1).

Connections

  • Lambda Expressions — the modern replacement for most std::bind uses
  • Function Pointers — the low-level callable std::function can wrap
  • Functors and operator() — class-based callables
  • Templates and Type Erasure — the mechanism behind std::function
  • Callbacks and Event Systems — primary real-world use of std::function
  • std::ref and std::cref — needed to pass references through bind

Concept Map

includes

includes

includes

includes

must match

must match

must match

must match

defines type of

achieved via

unifies types for

if unset

pre-fills args

stored in

Callables in C++

Free function

Lambda unique type

Functor operator

Member function ptr

Call signature R Args

std::function wrapper

Type erasure

Vector of callbacks

Empty throws bad_function_call

std::bind partial application

New callable fewer args

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Dekho, C++ me normally function ko hum direct call karte hain. Lekin kabhi aisa hota hai ki hume function ko ek variable me store karna hota hai, ya ek list me daalna hota hai (jaise "ye sab kaam baad me karne hain"). Problem ye hai ki har callable ka type alag hota hai — free function ka alag, har lambda ka apna unique type, functor ka alag. Inko ek hi container me daalna mushkil hai. Yahin std::function<R(Args...)> aata hai: ye ek uniform wrapper hai jo bolta hai "mujhe matlab nahi tu kaun hai, bas tujhe f(a,b) ki tarah call kar saku aur R mile" — isi ko type erasure kehte hain.

std::bind ka kaam hai partial application. Maan lo function hai sub(a,b). Agar tum a=10 fix kar do to ek naya function ban jaata hai g(b) = sub(10,b). Placeholders _1, _2 batate hain ki baaki arguments kahan jayenge. Yaad rakho: _1 ka matlab hai "jab user baad me bound object ko call karega, uska pehla argument" — ye bind list ka position nahi hai. Aur _2, _1 likh ke tum arguments ka order bhi swap kar sakte ho.

Do important traps: pehla, std::bind arguments ko copy karta hai, reference chahiye to std::ref(x) use karo. Doosra, empty std::function ko call karoge to std::bad_function_call throw hota hai, isliye if(f) f(); check karo. Aur ek aur baat — std::function zero-cost nahi hai, ye heap allocate kar sakta hai aur indirect call use karta hai, to hot loops me templates ya auto lambda better hai.

Modern advice (80/20): aaj kal std::bind ki jagah lambda use karo, zyada clear aur fast hota hai. std::function zaroor seekho kyunki callbacks aur event systems me bahut kaam aata hai. Bind ko sirf itna seekho ki purana code padh sako. Mantra: "FUNCTION = universal remote, BIND = pehle se dabaya hua button."

Go deeper — visual, from zero

Test yourself — C++ Programming

Connections