Skip to main content
Be Bitwise
C++Modern C++ Patterns

Type Erasure & Variant

C++ gives you several ways to work with values whose type isn't known at compile time. Where C hands you void* and a prayer, modern C++ offers type safety, automatic lifetime management, and pattern matching through visitors.

std::variant: A Type-Safe Union

std::variant holds one of several predefined types, like a C union but with type safety:

cpp
#include <variant>
#include <string>
#include <iostream>
std::variant<int, double, std::string> value;
value = 42; // holds int
value = 3.14; // now holds double
value = "hello"; // now holds string
// Access with std::get (throws if wrong type)
std::string& s = std::get<std::string>(value);
// Safe access with get_if (returns nullptr if wrong type)
if (auto* p = std::get_if<int>(&value)) {
std::cout << "It's an int: " << *p << "\n";
}
// Check which type is active
std::cout << "Index: " << value.index() << "\n"; // 2 (string)
Key Concept

A std::variant tracks which alternative it currently holds and enforces that at runtime. Reach for the wrong type and you get a std::bad_variant_access exception. A C union would have happily handed you whatever bytes happened to be sitting there.

One gotcha in the converting assignment is worth predicting:

cpp
std::variant<bool, std::string> v = "hello";
Which alternative does v hold?

Under the original C++17 rules, bool. A string literal decays to const char*, and pointer-to-bool is a standard conversion, which beats the user-defined conversion to std::string. C++20 (paper P0608) tightened the converting constructor so narrowing and pointer-to-bool conversions no longer count, and v now holds the string. Writing std::string("hello") sidesteps the question on any compiler.

std::visit: Pattern Matching

std::visit applies a visitor to the value stored in a variant:

cpp
#include <variant>
#include <string>
#include <iostream>
using Value = std::variant<int, double, std::string>;
void print_value(const Value& v) {
std::visit([](const auto& val) {
std::cout << val << "\n";
}, v);
}
// More specific handling with overloaded lambdas
template <typename... Ts>
struct overloaded : Ts... { using Ts::operator()...; };
template <typename... Ts>
overloaded(Ts...) -> overloaded<Ts...>;
void describe(const Value& v) {
std::visit(overloaded{
[](int i) { std::cout << "Integer: " << i << "\n"; },
[](double d) { std::cout << "Double: " << d << "\n"; },
[](const std::string& s) { std::cout << "String: " << s << "\n"; },
}, v);
}

The overloaded helper fuses several lambdas into one callable. It's the standard idiom for building visitors and you'll see it everywhere.

Under the hood a Value is a union-sized buffer plus a small index. With libstdc++ on x86-64 the buffer is 32 bytes (the size of std::string), the index is one byte after it, and alignment pads the whole thing to 40. std::visit reads the index and jumps through a table to the lambda for that alternative, which then reads only the bytes its type uses:

std::monostate: The Empty State

A std::variant is never empty by default — the first alternative gets default-constructed for you. When you actually want a null-ish state, slot std::monostate in as the first type:

cpp
#include <variant>
using OptionalInt = std::variant<std::monostate, int>;
OptionalInt maybe; // Default: monostate (empty)
maybe = 42;
if (std::holds_alternative<std::monostate>(maybe)) {
std::cout << "No value\n";
} else {
std::cout << std::get<int>(maybe) << "\n";
}

monostate is an empty state you chose. There's also one you didn't: if switching to a new alternative throws after the old value has already been destroyed, the variant is left holding nothing at all. valueless_by_exception() then returns true, index() returns std::variant_npos, and std::visit throws std::bad_variant_access.

Building a JSON Value Type

Here's where this earns its keep — a type-safe JSON value:

cpp
#include <variant>
#include <string>
#include <vector>
#include <map>
#include <memory>
#include <iostream>
// Forward declaration for recursive type
struct JsonValue;
using JsonNull = std::monostate;
using JsonBool = bool;
using JsonNumber = double;
using JsonString = std::string;
using JsonArray = std::vector<JsonValue>;
using JsonObject = std::map<std::string, JsonValue>;
struct JsonValue {
std::variant<
JsonNull,
JsonBool,
JsonNumber,
JsonString,
std::shared_ptr<JsonArray>,
std::shared_ptr<JsonObject>
> data;
// Constructors for convenience
JsonValue() : data(JsonNull{}) {}
JsonValue(bool b) : data(b) {}
JsonValue(double n) : data(n) {}
JsonValue(int n) : data(static_cast<double>(n)) {}
JsonValue(const char* s) : data(std::string(s)) {}
JsonValue(std::string s) : data(std::move(s)) {}
bool is_null() const {
return std::holds_alternative<JsonNull>(data);
}
bool is_bool() const {
return std::holds_alternative<JsonBool>(data);
}
bool is_number() const {
return std::holds_alternative<JsonNumber>(data);
}
bool is_string() const {
return std::holds_alternative<JsonString>(data);
}
};

Nothing forces those shared_ptrs on you. A std::vector<JsonValue> only stores a pointer to its elements, and since C++17 vector is allowed to be instantiated with an incomplete element type, so JsonArray could sit in the variant directly. std::map has no such guarantee in the standard, although libstdc++ and libc++ both accept it. The pointers do change copying: copy a JsonValue holding an array and both copies share, and can mutate, the same array.

Type Erasure by Hand

Everything so far deals with a closed list of types. Type erasure is how std::function and std::any hold types they've never heard of: a private virtual interface, a class template that implements it for whatever you store, and a value-semantic wrapper on top so callers never see a pointer. The runner on this site compiles C++14, which has no std::variant, but this technique needs nothing newer.

Try itAdd a struct Triangle and a draw(const Triangle&) overload above main, push one into the scene, and run it: Drawable itself never changes.
C++ (GCC 9.2.0)

That's the trade-off in miniature. Drawable is open to new types the way virtual functions are, but it keeps value semantics, and the types it holds don't inherit from anything.

std::any: Fully Dynamic Types

When you genuinely don't know the possible types until runtime, std::any holds any copyable value:

cpp
#include <any>
#include <string>
#include <iostream>
std::any value = 42;
std::cout << std::any_cast<int>(value) << "\n";
value = std::string("hello");
std::cout << std::any_cast<std::string>(value) << "\n";
// Wrong type throws std::bad_any_cast
try {
auto x = std::any_cast<double>(value);
} catch (const std::bad_any_cast& e) {
std::cerr << "Wrong type: " << e.what() << "\n";
}

Think of std::any as a type-safe void*. Plugin systems lean on it, as do configuration stores — anywhere the type is genuinely unknowable at compile time.

Choosing Between variant, any, and Polymorphism

Featurestd::variantstd::anyVirtual functions
Types known at compile timeYesNoPartially
Value semanticsYesYesNo (pointer/ref)
Heap allocationNoPossibleUsually
Pattern matching (visit)YesNoNo
Open for extensionNoYesYes

Reach for variant when the set of types is closed and known. any is the escape hatch when you genuinely don't know. Virtual functions still win when you need an open set of types sharing common behaviour and you're happy paying for indirection.

Real-World Applications

  • Error handling: std::variant<Result, Error> as a result type
  • AST nodes: Each node type is a variant alternative
  • Configuration values: variant<bool, int, double, string>
  • State machines: Each state is a variant alternative, transitions use visit

Challenges

Create a JsonValue type using std::variant that can hold null, bool, double, or std::string. Create one of each, and print their types using std::visit. Output should be: null bool double string (each on its own line).

C++ (GCC 9.2.0)