C++如何检查std::map中std::any元素的类型?
判断std::any中存储的类型(整数、std::string、枚举)
针对你定义的std::map<std::string, std::any> map_,遍历过程中判断it.second的类型可以借助std::any_cast和类型特性来实现,以下是具体方案:
1. 判断是否为整数类型
由于整数包含int、long、short、unsigned int等多种基础类型,需要逐个检查常见的整数类型是否匹配:
#include <any> #include <string> #include <map> // 辅助函数:判断std::any是否存储任意整数类型 bool isInteger(const std::any& val) { return std::any_cast<int>(&val) != nullptr || std::any_cast<long>(&val) != nullptr || std::any_cast<short>(&val) != nullptr || std::any_cast<unsigned int>(&val) != nullptr || std::any_cast<unsigned long>(&val) != nullptr || std::any_cast<char>(&val) != nullptr || std::any_cast<unsigned char>(&val) != nullptr; } // 遍历判断示例 void checkIntegerType(const std::map<std::string, std::any>& map_) { for (const auto& [key, val] : map_) { if (isInteger(val)) { // 处理整数类型,可根据实际需要用对应类型的any_cast取出值 if (auto pInt = std::any_cast<int>(&val)) { // 是int类型,*pInt即为值 } else if (auto pLong = std::any_cast<long>(&val)) { // 是long类型 } } } }
2. 判断是否为std::string类型
直接用std::any_cast<std::string>尝试获取指针,非空则说明存储的是std::string:
void checkStringType(const std::map<std::string, std::any>& map_) { for (const auto& [key, val] : map_) { if (auto pStr = std::any_cast<std::string>(&val)) { // 是std::string类型,*pStr即为字符串值 std::string content = *pStr; // 后续处理逻辑 } } }
也可以通过typeid直接比较类型:
if (val.type() == typeid(std::string)) { // 确认是std::string类型 }
3. 判断是否为枚举类型
C++标准中,std::any的类型擦除会丢失泛型的枚举特性,因此需要明确知道可能的枚举类型才能准确判断:
假设你有枚举类型Color和Size:
enum class Color { Red, Green, Blue }; enum Size { Small, Medium, Large };
判断时直接用对应枚举类型的std::any_cast检查:
void checkEnumType(const std::map<std::string, std::any>& map_) { for (const auto& [key, val] : map_) { // 判断是否为Color枚举 if (auto pColor = std::any_cast<Color>(&val)) { // 处理Color枚举,*pColor即为枚举值 } // 判断是否为Size枚举 else if (auto pSize = std::any_cast<Size>(&val)) { // 处理Size枚举 } } }
如果无法提前预知所有枚举类型,标准C++没有直接的方法判断std::any中的值是否为任意枚举类型(因为RTTI无法直接获取类型的枚举特性),这种情况下建议存储时额外记录类型标记(比如在map的key中隐含类型,或者用std::variant替代std::any,后者更适合已知类型集合的场景)。
内容的提问来源于stack exchange,提问作者Venelin
相关产品推荐
相关产品推荐

