Home > Software engineering >  Combining static_cast and std::any_cast
Combining static_cast and std::any_cast

Time:12-12

Is there any safe std::any_cast and static_cast combination?

I'm trying to perform the following:

#include <any>
#include <iostream>

int main( )
{
    auto x = std::make_any< int >( 5 );
#if 0 // doesn't work
    std::cout << std::any_cast< short >( x );
#else // works, but requires knowing the initial type
    std::cout << static_cast< short >( std::any_cast< int >( x ) );
#endif
}

CodePudding user response:

The only way to get a value out of std::any is any_cast<T> where T has the same typeid as the value inside (you can inspect it with .type() method).

If you need other semantics, e.g. "take a value iff it's convertible to int", you have to use something else for type erasure. For example, you can write one yourself.

CodePudding user response:

The fact is, that std::any cannot make sense of the data that is stores.

You may think that there is a member function type(), so std::any can know the type. But actually, that does not help, because the only thing you can do with the result of type() is to compare it to some other typeid. That is, you must already know for which type you are checking. Consequently, std::any cannot really answer the question "which type do you carry?"; it can only answer the question "do you carry this type X?".

The latter happens when you call std::any_cast<short>: std::any only knows that it does not carry a short, but it does not really know that it carries a type that is convertible to short.

  • Related