c++ - 在没有 RTTI 的情况下检查 std::any 的类型

标签 c++ types rtti stdany

我正在使用 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/

相关文章:

javascript - 编译 TypeScript 时忽略类型错误,但不忽略语法错误

android - 如果我的代码使用 RTTI 那么它不能在 android 上运行?

c++ - 从 Circle 类 C++ 返回 bool 值

c++ - 如何从单个C++ return语句返回多个值中的一个?

Scala 它是如何发生的以及为什么

c++ - typeid(T) 是在运行时还是编译时求值?

delphi - 如何在Delphi中获取方法参数名称数组/列表?

c++ - 调试 C++ 程序时遇到问题

c++ - 我可以在 C++ 中有一个 "type of types"吗?

swift - 类型转换与 swift 中的通用协议(protocol)冲突?