4

If I have a std::any of an std::string or an int, how could I cast this into the type that's contained?

std::any has type on it, however I can't use this type to cast.

Example:

#include <any>
#include <iostream>
#include <string>

int main(void) {
    std::any test = "things";
    std::any test2 = 123;

    // These don't work
    std::string the_value = (std::string) test;
    int the_value2 = (int) test2;

    std::cout << the_value << std::endl;
    std::cout << the_value2 << std::endl;
}
Mankarse
  • 39,818
  • 11
  • 97
  • 141
innectic
  • 275
  • 3
  • 12

2 Answers2

10

You use any_cast to do the trick. For example

auto a = std::any(12); 
std::cout << std::any_cast<int>(a) << '\n'; 

You can find more details from cppreference

If you want to dynamically cast the value inside a std::any, you can try

if (a.type() == typeid(int)) {
    cout << std::any_cast<int>(a) << endl;
} else if (a.type() == typeid(float)) {
    cout <<  std::any_cast<float>(a) << endl;
}
CS Pei
  • 10,869
  • 1
  • 27
  • 46
6

If you do not have a list of types among which the any holds one, you cannot convert the any to its type and operate on it as its real type.

You can store a type in an any, and an operation in that type as a function pointer on that any. But this must be done at the moment of storage or when you do have a list (possibly with 1 element) of the possible types stored in the any.

C++ does not store sufficient information within an any to permit arbitrary code to be compiled on that type when it stores the value in the any. C++ does not permit full "reification" at runtime.

Type erasing type erasure, `any` questions? Q&A by a stackoverflow user of ill repute gives an example of how to remember some operation on the contents of the any while still forgetting the type stored.

If you do have such a list of possible types, consider using variant. any exists in the narrow window where you do not know the types stored at container design time, but do at both insert and removal.

In that narrow window, you can do runtime tests based off the typeid stored and cast to the known type using any_cast.

Yakk - Adam Nevraumont
  • 262,606
  • 27
  • 330
  • 524