You need to enable JavaScript to run this app. 如何实现C++ TMP中多个Vector模板按位乘积的zip元函数
优惠活动
大模型
产品
解决方案
定价
更多

如何实现C++ TMP中多个Vector模板按位乘积的zip元函数

C++ TMP 实现zip元函数完整方案

实现思路

  • 基于第一个输入Vector的长度生成对应长度的编译期索引序列
  • 对每个索引位置,通过折叠表达式计算所有输入Vector对应下标的元素乘积
  • 将所有位置的乘积结果打包为新的Vector返回
  • 代码基于C++17及以上标准实现,用到了折叠表达式和index_sequence特性

完整代码实现

#include <type_traits>
#include <utility>
#include <array>

// 题目给定的Vector定义
template<int... Xs> struct Vector;

// 辅助元函数:获取Vector的第I个元素
template<std::size_t I, typename Vec>
struct get_nth_element;

template<std::size_t I, int... Xs>
struct get_nth_element<I, Vector<Xs...>>
{
    static constexpr int value = std::get<I>(std::array<int, sizeof...(Xs)>{Xs...});
};

template<std::size_t I, typename Vec>
constexpr int get_nth_element_v = get_nth_element<I, Vec>::value;

// zip前置声明
template<typename... Vectors>
struct zip;

// 偏特化:接收索引序列遍历每个位置计算乘积
template<typename... Vectors, std::size_t... Is>
struct zip<std::index_sequence<Is...>, Vectors...>
{
    // 两层展开:外层遍历所有索引,内层折叠计算同位置所有元素的乘积
    using type = Vector< ((get_nth_element_v<Is, Vectors>) * ...) ... >;
};

// 主模板实现:生成索引序列转发到偏特化
template<typename FirstVec, typename... RestVecs>
struct zip<FirstVec, RestVecs...>
{
    // 提取Vector的参数包生成对应长度的索引序列
    template<typename Vec> struct get_vector_seq;
    template<int... Xs> struct get_vector_seq<Vector<Xs...>> {
        using type = std::index_sequence_for<Xs...>;
    };
    using index_seq = typename get_vector_seq<FirstVec>::type;
    // 可选:添加静态断言校验所有输入Vector长度一致
    // static_assert(
    //     (std::is_same_v<index_seq, typename get_vector_seq<RestVecs>::type> && ...),
    //     "所有输入Vector的长度必须相同"
    // );
    using type = typename zip<index_seq, FirstVec, RestVecs...>::type;
};

// 题目要求的静态断言校验
static_assert(
    std::is_same<
        zip<Vector<1, 2, 3>, Vector<2, 3, 4>, Vector<3, 4, 5>>::type, 
        Vector<6, 24, 60>>::value);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 08:51:00