Use std::any for Type Safety
Learn to employ std::any for type safety.
We'll cover the following...
Introduced with C++17, the std::any
class provides a type-safe container for a single object of any type.
For example, this is a default-constructed any
object:
any x{};
This object has no value. We can test that with the has_value()
method:
if(x.has_value()) cout << "have value\n";else cout << "no value\n";
Output:
no value
We assign a value to the any
object with the assignment operator:
x = 42;
Now, the any
object has a value, and a type:
if(x.has_value()) {cout << format("x has type: {}\n", x.type().name());cout << format("x has value: {}\n", any_cast<int>(x));} else {cout << "no value\n";}
Output:
x has type: ix has value: 42
The type()
method returns a type_info
object. The type_info::name()
method returns an implementation-defined name for the type in a C-string. In this case, for GCC, the i
means int
. We use the any_cast<
...