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"]);
额外建议
- 类型检查:不确定存储类型时,可先用
std::any::type()验证类型匹配:if (expected["getVector"].type() == typeid(std::vector<int>)) { auto getVector = std::any_cast<std::vector<int>>(expected["getVector"]); // 处理vector逻辑 } - 键存在性检查:使用
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
相关产品推荐
相关产品推荐

