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

如何从枚举映射数组自动生成std::variant类型定义?

从constexpr枚举数组自动生成std::variant类型

核心思路

利用C++的索引序列和decltype类型推导,遍历constexpr枚举数组的每个元素,自动提取对应的原生类型并打包成std::variant,无需手动编写数十个类型参数。

步骤实现

1. 基础类型映射定义

先确保typeify_t类型特性正常工作,示例如下:

#include <variant>
#include <array>
#include <string>
#include <type_traits>

enum class MyTypes { Int, Float, String, Bool /* ... 其他50+枚举值 */ };

// 枚举到原生类型的映射模板
template<MyTypes T> struct typeify;
template<> struct typeify<MyTypes::Int> { using type = int; };
template<> struct typeify<MyTypes::Float> { using type = float; };
template<> struct typeify<MyTypes::String> { using type = std::string; };
template<> struct typeify<MyTypes::Bool> { using type = bool; };
// ... 补充其他枚举值的特化

template<MyTypes T> using typeify_t = typename typeify<T>::type;

// 存储枚举与名称映射的constexpr数组(示例)
constexpr std::array<MyTypes, 4> KnownTypes = {
    MyTypes::Int, MyTypes::Float, MyTypes::String, MyTypes::Bool
};

2. 自动生成Variant的辅助模板

通过索引序列遍历数组元素,推导对应的类型参数包:

// 辅助函数(仅用于类型推导,无需实现)
template<std::size_t... Idx>
auto make_variant_from_array_impl(std::index_sequence<Idx...>) 
    -> std::variant<typeify_t<KnownTypes[Idx]>...>;

// 提取推导后的variant类型
template<typename Seq>
using make_variant_from_array_t = decltype(make_variant_from_array_impl(Seq{}));

3. 最终生成目标Variant类型

利用std::make_index_sequence生成数组长度对应的索引序列,得到最终的std::variant:

// 自动生成包含所有对应类型的variant
using MyVariant = make_variant_from_array_t<std::make_index_sequence<KnownTypes.size()>>;

验证正确性

可以通过静态断言确认生成的类型符合预期:

// 验证生成的variant类型是否正确
static_assert(std::is_same_v<MyVariant, std::variant<int, float, std::string, bool>>);

兼容性说明

  • 该方案兼容C++17(依赖std::variant和C++14引入的std::index_sequence)
  • 数组长度不管是50还是更多,都能自动适配,无需修改模板代码

内容的提问来源于stack exchange,提问作者DBS4261

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 00:53:19