gpt4 book ai didi

c++ - 如何基于某些派生类型制作元组?

转载 作者:搜寻专家 更新时间:2023-10-31 01:08:54 24 4
gpt4 key购买 nike

例如,我有类型

template<unsigned i> struct Element;

template struct Element<0> {typedef int Type};
template struct Element<1> {typedef float Type};
template struct Element<2> {typedef double Type};

static const int COUNT = 3;

并想创建一个元组类型为

std::tuple<Element<0>::Type, Element<1>::Type, Element<2>::Type>

如果 COUNT 是常量但不总是 3 怎么办?

最佳答案

基本上有两种方法,只是思路不同:Indices (当你有可用的(功能性)可变参数模板时),或者在你进行时手动构建元组(当你有 Visual C++ 时)。

指数:

template<unsigned... Is> struct seq{};
template<unsigned I, unsigned... Is>
struct gen_seq : gen_seq<I-1, I-1, Is...>{};
template<unsigned... Is>
struct gen_seq<0, Is...>{ using type = seq<Is...>; };

template<unsigned N, template<unsigned> class TT,
class Seq = typename gen_seq<N>::type>
struct tuple_over{};

template<unsigned N, template<unsigned> class TT, unsigned... Is>
struct tuple_over<N, TT, seq<Is...>>{
using type = std::tuple<typename TT<Is>::type...>;
};

手动递归:

template<unsigned N, template<unsigned> class TT, class TupleAcc = std::tuple<>>
struct tuple_over{
using tt_type = typename TT<N-1>::type;
// since we're going from high to low index,
// prepend the new type, so the order is correct
using cat_type = decltype(std::tuple_cat(std::declval<std::tuple<tt_type>>(), std::declval<TupleAcc>()));
using type = typename tuple_over<N-1, TT, cat_type>::type;
};

template<template<unsigned> class TT, class Tuple>
struct tuple_over<0, TT, Tuple>{ using type = Tuple; }

两个版本的用法相同:

using result = tuple_over<COUNT, Element>::type;

Live example for indices.
Live example for manual recursion.

关于c++ - 如何基于某些派生类型制作元组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17602761/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com