Basic std::variant use

suggest change

This creates a variant (a tagged union) that can store either an int or a string.

std::variant< int, std::string > var;

We can store either type in it:

var = std::string("hello");

And we can access the contents via std::visit:

// Prints "hello\n":
std::visit( [](auto&& e) {
  std::cout << e << '\n';
}, var );

by passing in a polymorphic lambda or similar function object.

If we are certain we know what type it is, we can get it:

auto str = std::get<std::string>(var);

but this will throw std::bad_variant_access if we get it wrong. get_if:

auto* str  = std::get_if<std::string>(&var);

returns nullptr if you guess wrong.

A std::variant itself does not allocate dynamic memory, other than what its contained types allocate. Only one alternative is stored. If assignment throws and the variant cannot keep either the old or the new value, it becomes valueless_by_exception.

Variants let you store multiple value types in one variable safely and efficiently. They are basically smart, type-safe unions.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents