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

如何将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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 13:24:09