Helloer
Helloer

Reputation: 467

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?

Upvotes: 3

Views: 804

Answers (1)

peoro
peoro

Reputation: 26060

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;
}

Upvotes: 5

Related Questions