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

如何在C++中按指定次数重复模板参数生成std::tuple类型?

实现方案

当然可以实现这个需求,以下是几种不同C++版本下的具体实现方式:

方法一:C++17及以上(折叠表达式,最简洁)

利用折叠表达式对模板参数包展开,为每个参数对应生成一个int类型,最终组合成std::tuple:

#include <tuple>
#include <type_traits>

template<typename... Types>
class MyClass {
public:
    // 对每个Types中的类型,展开生成一个int
    using MyDataType = std::tuple<decltype((void)Types{}, int)...>;
    MyDataType MyData;
};

// 验证示例:确认类型符合预期
static_assert(std::is_same_v<
    MyClass<int, float, std::string, double>::MyDataType,
    std::tuple<int, int, int, int>
>);

说明

decltype((void)Types{}, int)的作用是:

  • (void)Types{}:仅用于触发参数包的逐个展开,不会实际构造类型对象(void转换会忽略表达式值,即使Types中的类型无法默认构造也能正常工作)
  • 最终每个展开项的类型都是int,因此参数包有多少个类型,std::tuple就会包含多少个int

方法二:C++14及以上(利用索引序列)

如果使用C++14,可以借助std::index_sequence和辅助函数来生成目标tuple类型:

#include <tuple>
#include <utility>
#include <type_traits>

// 辅助函数,根据索引序列生成对应数量的int组成的tuple
template<std::size_t... Is>
auto make_tuple_of_ints(std::index_sequence<Is...>) -> std::tuple<decltype(Is, int)...>;

template<typename... Types>
class MyClass {
public:
    // 生成与参数包大小相同的索引序列,再转换为tuple类型
    using MyDataType = decltype(
        make_tuple_of_ints(std::make_index_sequence<sizeof...(Types)>{})
    );
    MyDataType MyData;
};

// 验证示例:确认类型符合预期
static_assert(std::is_same_v<
    MyClass<int, float, std::string, double>::MyDataType,
    std::tuple<int, int, int, int>
>);

说明

  • std::make_index_sequence<sizeof...(Types)>会生成一个包含0, 1, ..., N-1的索引序列(N是参数包的大小)
  • 辅助函数make_tuple_of_ints接收这个序列后,将每个索引转换为int类型,最终组合成目标tuple

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 11:05:47