Accessing The Stored Value

Here are discussed the different modes of accessing a stored value in std::any.

To access the currently active value in std::any you have one option:

std::any_cast<T>().

The function has three “modes” you can work with:

  • read access - takes std::any as a reference, returns a copy of the value, throws std::bad_any_cast when it fails
  • read/write access - takes std::any as a reference, returns a reference, throws std::bad_any_cast when it fails
  • read/write access - takes std::any as a pointer, returns a pointer to the value (const or not) or nullptr

Concisely:

std::any var = 10;

// read access:
auto a = std::any_cast<int>(var);

// read/write access through a reference:
std::any_cast<int&>(var) = 11;

// read/write through a pointer:
int* ptr = std::any_cast<int>(&var);
*ptr = 12;

See the example:

Get hands-on with 1400+ tech skills courses.