C++ · 7 · Advanced / Job-Ready33 / 36 · 92%
Type Erasure: function, any, variant
Store different types behind one interface — with or without inheritance.
Examples: std::function, std::any, std::variant, optional
shortcuts: ← prev · → next · M mark
1
std::function
Any callable with a matching signature.
Example
example
std::function<int(int,int)> op;
op = [](int a, int b){ return a + b; };
op = std::plus<int>{};
op = &add_function;
int r = op(2, 3);TIP
std::function may heap-allocate and always costs an indirect call. In a hot path take a template parameter or std::function_ref instead.
2
std::variant
A type-safe union — exactly one of a fixed list of types.
Example
example
std::variant<int, std::string, double> v = 42;
v = "hello";
std::visit([](const auto& x){ std::cout << x; }, v);
if (auto* s = std::get_if<std::string>(&v)) { /* ... */ }3
optional & expected
Model "maybe a value" and "value or error" without exceptions.
Example
example
std::optional<User> find_user(int id);
if (auto u = find_user(7)) std::cout << u->name;
// C++23
std::expected<Config, ParseError> parse(std::string_view text);4
std::any
Holds literally anything; you must know the type to get it back.
Example
example
std::any a = 42;
a = std::string("hi");
try { auto s = std::any_cast<std::string>(a); }
catch (const std::bad_any_cast&) { }Interview question
variant or inheritance?