如何将enum class枚举值映射为对应类型,生成匹配的std::tuple作为模板类成员
实现方案
核心思路
通过编译期模板特化建立枚举值到对应C++类型的映射,直接对传入的可变枚举参数包做展开生成tuple的类型列表,全程无全局变量、无运行时开销。
完整实现代码
#include <tuple> enum class Type { eInt, eFloat, eDouble }; // 枚举到类型的映射模板 template<Type t> struct TypeMap; // 特化每个枚举值对应类型 template<> struct TypeMap<Type::eInt> { using type = int; }; template<> struct TypeMap<Type::eFloat> { using type = float; }; template<> struct TypeMap<Type::eDouble> { using type = double; }; // 便捷别名简化调用 template<Type t> using TypeMap_t = typename TypeMap<t>::type; template <Type... type> class Test { public: private: // 展开参数包生成对应tuple类型 std::tuple<TypeMap_t<type>...> m_data; }; int main() { Test<Type::eDouble, Type::eInt> t1; // m_data类型为std::tuple<double, int> Test<Type::eInt, Type::eFloat> t2; // m_data类型为std::tuple<int, float> }
实现说明
- 所有映射逻辑都在编译期完成,不产生任何运行时代码或全局变量
- 如果后续需要新增枚举值和类型的对应关系,只需要新增
TypeMap的特化即可,无需修改现有逻辑 - 符合C++11及以上标准的编译器都可以正常编译运行
内容的提问来源于stack exchange,提问作者antho
相关产品推荐
相关产品推荐

