std::any
void*
(with a discriminator) to store objects of any type
assert (! a.has_value());
* initialisation with an object:
std::any a2 { 10 }; // int
std::any a3 { MyType { 10, 11 } };
* `in_place`:
std::any a4 { std::in_place_type
std::any a5 { std::in_place_type
* `make_any`
std::any a6 = std::make_any
## Changing the value:
* assignment operator:
std::any a;
a = MyType (10, 11);
a = std::string (“Hello”);
* `emplace`
a.emplace
a.emplace<std::vector
a.emplace
## Accessing:
std::any var = 10;
// read access (just copies)
auto a = std::any_cast
// read/write access through a reference: std::any_cast<int&> (var) = 11;
// read/write through a pointer:
int* ptr = std::any_cast
* Pointer will return nullptr if not the correct type
* Otherwise Will throw `std::bad_any_cast` if calling on an incorrect type
struct MyType { int a, b; MyType (int x, int y) : a (x), b (y) { } void print() { std::cout « a « ”, “ « b « ‘\n’; } };
int main()
{
std::any var = std::make_any
try
{
std::any_cast<MyType&> (var).print();
std::any_cast<MyType&> (var).a = 11; // read/write
std::any_cast<MyType&> (var).print();
std::any_cast<int> (var); // throw!
}
catch (const std::bad_any_cast& e)
{
std::cout << e.what() << '\n';
}
int* p = std::any_cast<int> (&var);
std::cout << (p ? "contains an int... \n" : "doesn't contain an int...\n");
if (MyType* pt = std::any_cast<MyType> (&var); pt)
{
pt->a = 12;
std::any_cast<MyType&> (var).print();
} }
OUTPUT:
10, 10 11, 10 bad any_cast doesn’t contain an int… 12, 10 ```