Search code examples
c++pointerscastingany

Casting specific pointer to std::any pointer


You can use any_cast to turn an std::any* type into a pointer of the original type. But how do you do the reverse?

string h = “str”;
string *j = &h;
std::any *hh = reinterpret_cast<any*>(j);
cout << (*hh).type().name();

It will not work. Whichever type I use, if I dereference the resulting pointer and access a member with a “.” or I use “->” to access the same member on the pointer my application fails.

I tried static_cast and dynamic_cast too but that would not even compile.


Solution

  • You don't want to use a std::any*. What you want is just a std::any. To put something into a std::any you use

    std::any anything_i_want;
    //...
    std::string some_string = "some text";
    anything_i_want = some_string;
    // now the any contains a `std::string`
    std::string another_string  = std::any_cast<std::string>(anything_i_want);
    // now we get the string out of the any