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

C++中如何在std::any中存储并检索std::vector等容器?

如何从std::any中检索聚合类型(如std::vector)?

在C++中使用std::map<std::string, std::any>构建单元测试的异构值映射时,int、double等基本类型的存取正常,但存储std::vector<int>后无法通过std::any_cast成功检索。

用户代码示例:

std::map<std::string, std::any> expected = {
    { "getInt", 1 },
    { "getDouble", 1.0 },
    { "getVector", std::vector<int> { 1, 2 } },
};

int getInt = std::any_cast<int>(expected["getInt"]);
double getDouble= std::any_cast<double>(expected["getDouble"]);

失败的检索代码:

std::vector<int> getVector= std::any_cast<std::vector>(expected["getVector"]);

问题原因与解决方法

问题出在std::any_cast的模板参数上:std::vector是模板类,并非具体类型,而std::any存储的是具体实例的完整类型(即std::vector<int>)。any_cast必须指定与存储类型完全匹配的模板参数才能成功转换。

修改后的正确检索代码:

std::vector<int> getVector = std::any_cast<std::vector<int>>(expected["getVector"]);

额外建议

  1. 类型检查:不确定存储类型时,可先用std::any::type()验证类型匹配:
    if (expected["getVector"].type() == typeid(std::vector<int>)) {
        auto getVector = std::any_cast<std::vector<int>>(expected["getVector"]);
        // 处理vector逻辑
    }
    
  2. 键存在性检查:使用operator[]会在键不存在时插入默认std::any,可能导致转换失败,建议先通过find确认键存在:
    auto it = expected.find("getVector");
    if (it != expected.end() && it->second.type() == typeid(std::vector<int>)) {
        auto getVector = std::any_cast<std::vector<int>>(it->second);
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 10:20:39