如何基于一些派生类型生成元组

How to make a tuple based on some derived types?

本文关键字:元组 类型 派生 何基于      更新时间:2023-10-16

例如,我有类型

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,该怎么办?

基本上有两种方法,仅在思想上不同:索引(当您有(功能性的)可变模板可用时),或在进行过程中手动构建元组(当您使用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;

指数的实例
手动递归的实例。

这里有一种可能的方法。给定您的类模板定义:

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; };

你可以利用通常的索引框架来写这样的东西:

#include <tuple>
namespace detail
{
    template<int... Is>
    struct seq { };
    template<int N, int... Is>
    struct gen_seq : gen_seq<N - 1, N - 1, Is...> { };
    template<int... Is>
    struct gen_seq<0, Is...> : seq<Is...> { };
    template<template<unsigned int> class TT, int... Is>
    std::tuple<typename TT<Is>::type...> make_tuple_over(seq<Is...>);
}
template<template<unsigned int> class TT, int N>
using MakeTupleOver = 
    decltype(detail::make_tuple_over<TT>(detail::gen_seq<N>()));

这就是你在程序中使用它的方式:

#include <type_traits> // For std::is_same
int main()
{
    static_assert(
        std::is_same<
            MakeTupleOver<Element, 3>, 
            std::tuple<int, float, double>
        >::value, "!");
}

这是一个的实际示例