是否存在安全的 std::any_cast
和 static_cast
组合?
我正在尝试执行以下操作:
#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
}
最佳答案
从 std::any
中获取值的唯一方法是 any_cast<T>
哪里T
有相同的 typeid
作为里面的值(您可以使用 .type()
方法检查它)。
如果您需要其他语义,例如“取一个值当且仅当它可以转换为 int
”,你必须使用其他东西来进行类型删除。例如,您可以自己编写一个。
关于c++ - 结合 static_cast 和 std::any_cast,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70313749/