c++typesrttistdany

Checking std::any's type without RTTI


I'm using std::any with RTTI and exceptions disabled. It works and std::any_cast<T>() is able to detect whether the type is correct as explained in std::any without RTTI, how does it work?. std::any::type() is disabled without RTTI though.

I'd like to check whether my std::any object contains a value of a given type. Is there any way to do that?


Solution

  • You can cast a pointer to your any value and check whether the result is null:

    #include <any>
    #include <iostream>
    
    int main( int argc, char** argv ) {
        std::any any = 5;
        
        if( auto x = std::any_cast<double>(&any) ) {
            std::cout << "Double " << *x << std::endl;
        }
        if( auto x = std::any_cast<int>(&any) ) {
            std::cout << "Int " << *x << std::endl;
        }
        
        return 0;
    }