Representing dynamic values with std::any

Just like std::optional, std::any can store an optional single value, but with the difference that it can store any type at runtime, just like a dynamically typed}language. As the std::any can withhold any type, you need to explicitly specify the type using the global function std::any_cast when reading the held object.

If the std::any is empty or withholds another type than the specified type, an exception is thrown.

Here is an example of how it works:

// Initialize an empty std::any auto a = std::any{}; // Put a string in it a = std::string{"something"}; // Return a reference to the withheld string auto& str_ref = std::any_cast<std::string&>(a); // Copy the withheld string auto str_copy = std::any_cast<std::string>(a); ...

Get C++ High Performance now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.