2

For example, I have types

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;

and want to make a tuple of type as

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

How to do it if the COUNT is constant but not always 3?

4

2 回答 2

2

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

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, "!");
}

这是一个活生生的例子

于 2013-07-11T20:36:57.833 回答
2

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

指数的活生生的例子。
手动递归的实时示例。

于 2013-07-11T20:40:39.213 回答