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); // Put a float in the 'any' and read it back a = 135.246f; auto flt = std::any_cast<float>(a); // Copy the any object auto b = a; auto is_same = (a.type() == b.type()) && (std::any_cast...