Skip to the workspace
Pebellslearn by building
Data Types  ›  Lesson

Dynamic Typing with variant and any

Dynamic Typing 12 minstd::variant stores one of a declared set of alternatives. std::any stores a value of a copy-constructible type with checked access. These containers remain statically typed themselves.

cpp / Dynamic Typing with variant and any

Explore each scene at your own pace.

01 · The rule

The rule

Dynamic Typing with variant and any

std::variant stores one of a declared set of alternatives. std::any stores a value of a copy-constructible type with checked access. These containers remain statically typed themselves.

Represent runtime alternatives with variant and compare their guarantees with any.

Rocket Run's settings screen has a volume (a whole number), a brightness (a decimal) and a nickname (text). You would like one map from setting name to value. But C++ variables have one fixed type. The standard library solves this without giving up safety: the container has a fixed type, and the value inside can vary at run time.

The rule

Known list of types: variant. Truly anything: any. Both check on access.

In a dynamically typed language like Python, a variable can hold an int now and a string later. C++ is static, so it offers two types that carry that flexibility inside them.

std::variant (header <variant>) holds exactly one value from a list you name:

using Setting = std::variant<int, double, std::string>;

Setting volume = 80;
Setting nickname = std::string("Nova");

if (std::holds_alternative<int>(volume)) {
    int v = std::get<int>(volume);    // 80
}
nickname = 3;                         // now it holds an int

Asking std::get for a type the variant does not currently hold throws std::bad_variant_access. To handle every possible type in one place, std::visit calls your code with whichever value is inside.

std::any (header <any>) holds a single value of any copyable type:

std::any extra = 5;
int n = std::any_cast<int>(extra);    // 5
double d = std::any_cast<double>(extra);  // throws std::bad_any_cast

any_cast needs the exact stored type: an int is not quietly converted to a double.

Old C code used void* for this job. It remembers no type at all, so a wrong guess is undefined behaviour rather than a clean exception.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.