问题描述
我正在将std::any
用于RTTI,并且禁用了例外。它可以正常工作,并且std::any_cast<T>()
能够检测类型是否正确,如std::any without RTTI,how does it work?中所述。 std::any::type()
会在没有RTTI的情况下被禁用。
我想检查我的std::any
对象是否包含给定类型的值。有什么办法吗?
解决方法
您可以将指针转换为any
值,并检查结果是否为空:
#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;
}