【问题标题】:Checking std::any's type without RTTI在没有 RTTI 的情况下检查 std::any 的类型
【发布时间】:2020-08-21 14:41:29
【问题描述】:

我正在使用 std::any 并禁用 RTTI 和异常。它可以工作并且std::any_cast<T>() 能够检测类型是否正确,如std::any without RTTI, how does it work? 中所述。 std::any::type() 在没有 RTTI 的情况下被禁用。

我想检查我的std::any 对象是否包含给定类型的值。有什么办法吗?

【问题讨论】:

  • 我不明白这个问题。你说any_cast 的检测即使没有 RTTI 也能正常工作。所以......只需使用它来检测它是什么类型。
  • @NicolBolas 异常也被禁用,因此错误的 any_cast 将使程序崩溃。
  • @user253751:如果您将指向 any 的指针转换为 T*,则不会。
  • 这能回答你的问题吗? std::any without RTTI, how does it work?

标签: c++ types rtti stdany


【解决方案1】:

您可以将指针转换为您的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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-23
    • 1970-01-01
    • 2020-06-28
    • 1970-01-01
    • 2023-03-20
    • 2011-12-12
    • 1970-01-01
    • 2022-11-03
    相关资源
    最近更新 更多