Object Creation
The different methods of in-place object creation are discussed briefly in this lesson.
We'll cover the following...
There are several ways you can create std::any
object:
- a default initialisation - then the object is empty
- a direct initialisation with a value/object
- in place
std::in_place_type
- via
std::make_any
You can see it in the following example:
Press + to interact
#include <string>#include <iostream>#include <any>#include <cassert>using namespace std;class MyType{int a, b;public:MyType(int x, int y) : a(x), b(y) { }};int main(){// default initialization:std::any a;assert(!a.has_value());// initialization with an object:std::any a2{10}; // intstd::cout << "a2 is: " << std::any_cast<int>(a2) << '\n';std::any a3{MyType{10, 11}};// in_place:std::any a4{std::in_place_type<MyType>, 10, 11};std::any a5{std::in_place_type<std::string>, "Hello World"};std::cout << "a5 is: " << std::any_cast<std::string>(a5) << '\n';// make_anystd::any a6 = std::make_any<std::string>("Hello World");std::cout << "a6 is: " << std::any_cast<std::string>(a6) << '\n';}