0Pricing
C++ Academy · Lesson

std::function Type-erased Callables

Erase types behind std::function and understand the small-buffer optimization.

The Problem: One Type for Many Callables

Each lambda has a unique type. Each function pointer is a different type. We need one type that can hold any of them — std::function.

Template Parameter

std::function<Signature> takes the return type and parameter types. It accepts anything callable with that signature.

#include <functional>
std::function<int(int, int)> op;
op = [](int a, int b) { return a + b; };
std::cout << op(3, 4);   // 7

All lessons in this course

  1. Function Objects Functors
  2. Lambda Captures by-value by-reference mutable
  3. Generic Lambdas and Closures C++14
  4. std::function Type-erased Callables
← Back to C++ Academy