我正在使用 std::any
禁用 RTTI 和异常。它有效并且std::any_cast<T>()
能够检测类型是否正确,如 std::any without RTTI, how does it work? 中所述. std::any::type()
虽然在没有 RTTI 的情况下被禁用。
我想检查一下我的 std::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;
}
关于c++ - 在没有 RTTI 的情况下检查 std::any 的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63524970/