C++基于名称映射枚举:隐藏库枚举并获取枚举名称方案咨询
实现方案
方案1:直接建立整数到目标字符串的映射
这是最直接的实现方式,既然已经明确返回值0对应"lib_a"、1对应"lib_b"、2对应"lib_c",直接通过硬编码映射完成转换,对外完全隔离第三方库的细节。
// 对外头文件(无需引入第三方库头文件) #include <string> std::string GetTypeString(int typeValue); // 内部实现文件(可引入第三方库头文件) #include <stdexcept> std::string GetTypeString(int typeValue) { switch(typeValue) { case 0: return "lib_a"; case 1: return "lib_b"; case 2: return "lib_c"; default: throw std::invalid_argument("Unknown type value"); } // 也可以用数组实现,更简洁: // static const std::string typeNames[] = {"lib_a", "lib_b", "lib_c"}; // if (typeValue >= 0 && typeValue < sizeof(typeNames)/sizeof(typeNames[0])) { // return typeNames[typeValue]; // } // throw std::invalid_argument("Unknown type value"); }
方案2:基于第三方枚举值建立映射(避免硬编码整数)
如果担心第三方库后续修改枚举的数值定义(比如把lib_c的值改成3),可以在内部实现中借助第三方枚举构建映射,这样枚举值变化时只需同步内部映射,对外依然完全隐藏第三方库。
// 对外头文件(同上,无需引入第三方库) #include <string> std::string GetTypeString(int typeValue); // 内部实现文件 #include "third_party_lib.h" // 引入第三方库头文件 #include <unordered_map> #include <stdexcept> std::string GetTypeString(int typeValue) { static const std::unordered_map<int, std::string> typeMap = { {static_cast<int>(LibTypes::lib_a), "lib_a"}, {static_cast<int>(LibTypes::lib_b), "lib_b"}, {static_cast<int>(LibTypes::lib_c), "lib_c"} }; auto it = typeMap.find(typeValue); if (it != typeMap.end()) { return it->second; } throw std::invalid_argument("Unknown type value"); }
结合自定义Types枚举的方案
如果你想先将返回值转换为自己定义的Types枚举,再映射到第三方库的枚举名称,可以通过两步转换实现,对外只暴露你自己的枚举类型:
// 对外头文件(仅包含自定义枚举) enum Types{ a, b, c }; #include <string> std::string GetTypeString(int typeValue); std::string GetTypeString(Types type); // 可选:提供直接转换自定义枚举的接口 // 内部实现文件 #include "third_party_lib.h" #include <stdexcept> std::string GetTypeString(int typeValue) { Types myType; switch(typeValue) { case static_cast<int>(LibTypes::lib_a): myType = Types::a; break; case static_cast<int>(LibTypes::lib_b): myType = Types::b; break; case static_cast<int>(LibTypes::lib_c): myType = Types::c; break; default: throw std::invalid_argument("Unknown type value"); } return GetTypeString(myType); } std::string GetTypeString(Types type) { switch(type) { case Types::a: return "lib_a"; case Types::b: return "lib_b"; case Types::c: return "lib_c"; default: throw std::invalid_argument("Unknown type"); } }
内容的提问来源于stack exchange,提问作者Sarmad
相关产品推荐
相关产品推荐

