cpp17 · medium

C++17: std::any

std::any (C++17) stores a single value of any copy-constructible type and remembers that type at runtime, acting as a type-safe alternative to void*. Extraction uses any_cast: the value form std::any_cast<T>(a) returns a T but throws std::bad_any_cast on a type mismatch, while the pointer form std::any_cast<T>(&a) returns T* or nullptr and is the no-throw way to probe; both require the exact stored type with no implicit conversions. Among the C++17 vocabulary types, choose the narrowest: std::optional<T> for value-or-nothing, std::variant for a closed and known set of alternatives (compile-time checked, exhaustively visitable, usually no heap or RTTI), and std::any only when the type set is genuinely open. any is the heaviest — it pays an RTTI check and may heap-allocate large types (small ones can use a small-buffer optimization).

🔑 Key line

C++17 std::any is a type-safe void*: it holds one value of any copyable type and its type; any_cast<T>(a) throws bad_any_cast on mismatch while any_cast<T>(&a) returns nullptr — prefer variant for a closed type set.

The code

#include <any>
std::any a = 42; // holds an int
a = std::string("hello"); // now holds a string (type-safe)
if (a.type() == typeid(std::string))
std::string s = std::any_cast<std::string>(a); // by value/ref
auto* p = std::any_cast<int>(&a); // pointer form: nullptr if wrong
if (!p) /* a does not currently hold an int */;
a.reset(); // now empty: a.has_value() == false

What this lesson walks through

  1. 01A type-safe void*
  2. 02any_cast: value form throws, pointer form is safe
  3. 03Gotcha — any_cast throws (or returns null)
  4. 04any vs variant vs optional

std::any is a container for a single value of any copy-constructible type, remembering that type at runtime. Unlike void*, it is type-safe: extracting the wrong type throws (or returns nullptr in the pointer form). Use it when the set of types is genuinely open/unknown — config values, plugin payloads, scripting glue.

See it animated — step by step, at your own pace

Unlock the full interactive walkthrough of C++17: std::any and 100+ animated C++ interview lessons.

← Previous
C++17: Fold Expressions
Next →
C++17: if / switch With Initializer