You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Visual Studio中查看std::any的数值与类型方法咨询

std::any类型判断与安全取值方案

获取存储的类型信息

  • 通过std::any::type()获取存储对象的std::type_info,可直接与typeid()结果对比,确认类型:
    if (e.type() == typeid(float)) {
        // 确认存储的是float类型
    }
    
  • 调用std::type_info::name()可获取类型名称(注意名称格式依赖编译器,比如VS中float显示为"float")。

未知类型时的安全取值方法

1. 枚举预判的可能类型

如果能确定std::any的潜在类型范围,逐个判断后取值:

#include <any>
#include <iostream>

int main() {
    std::any e = 1.0f;
    if (e.type() == typeid(float)) {
        float val = std::any_cast<float>(e);
        std::cout << "值: " << val << ", 类型: float" << std::endl;
    } else if (e.type() == typeid(int)) {
        int val = std::any_cast<int>(e);
        std::cout << "值: " << val << ", 类型: int" << std::endl;
    }
    // 可扩展其他类型判断
    return 0;
}

2. 使用指针版本的std::any_cast

这是最安全的方式,类型不匹配时返回nullptr,不会抛出异常或导致调试器崩溃:

float* float_val = std::any_cast<float>(&e);
if (float_val != nullptr) {
    std::cout << "Float值: " << *float_val << std::endl;
} else {
    std::cout << "存储的类型不是float" << std::endl;
}

解决无效类型std::any_cast导致的调试崩溃

  • 优先用指针版本:从根源避免异常和崩溃,类型不匹配仅返回空指针。
  • 若必须使用值版本,用try-catch捕获std::bad_any_cast异常:
try {
    float val = std::any_cast<float>(e);
} catch (const std::bad_any_cast& ex) {
    std::cerr << "类型不匹配: " << ex.what() << std::endl;
    // 此处处理类型不匹配逻辑,不会崩溃
}

调试模式下VS默认会在抛出异常时中断,可通过调试设置关闭“C++异常”的第一次机会中断,但更推荐指针版本的方案。

内容的提问来源于stack exchange,提问作者Michael Chourdakis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 21:40:27