Transform tuple to “triangular” tuple

和自甴很熟 提交于 2021-02-10 06:54:31

问题


How do I transform this type:

std::tuple<T0, T1, ..., TN1, TN>

into this:

std::tuple<
  std::function<T0()>,
  std::function<T1(T0)>,
  std::function<T2(T0, T1)>,
  ...
  std::function<TN(T0, ..., TN1 )>
>

回答1:


Right ... isn't suffice, but you could always use pattern matching (i.e. partial specialization) with recursion:

#include <tuple>
#include <functional>
#include <cstdlib>

// A type to store list of integers 
template <size_t... ns>
struct integers
{
    template <size_t n>
    using push_back = integers<ns..., n>;
};

// This generates 'integers<0, 1, 2, ..., n-1>'
template <size_t n>
struct iota
{
    typedef typename iota<n-1>::type::template push_back<n-1> type;
};
template <>
struct iota<0>
{
    typedef integers<> type;
};

// Put a type to the front of the argument list
template <typename T, typename U>
struct push_front;
template <typename T, typename R, typename... A>
struct push_front<R(A...), T>
{
    typedef R type(T, A...);
};

// This converts 'std::tuple<T0, T1, ..., TN>' to the function type
// 'TK(T0, T1, ..., TK-1)' where K is the first parameter
template <size_t, typename...>
struct slice;
template <size_t end, typename First, typename... Rest>
struct slice<end, First, Rest...>
{
    typedef typename push_front<typename slice<end-1, Rest...>::type, First>::type type;
};
template <typename First, typename... Rest>
struct slice<0, First, Rest...>
{
    typedef First type();
};

// This calls 'slice' on T... for all integers in the list.
template <typename T, typename U>
struct triangularize_impl;
template <typename... T, size_t... n>
struct triangularize_impl<std::tuple<T...>, integers<n...>>
{
    typedef std::tuple<std::function<typename slice<n, T...>::type>...> type;
};

// This is a wrapper of 'triangularize_impl'.
template <typename T>
struct triangularize;
template <typename... T>
struct triangularize<std::tuple<T...>>
{
    typedef typename triangularize_impl<std::tuple<T...>, typename iota<sizeof...(T)>::type>::type type;
};

As a demo, in g++ 4.7 when we write

triangularize<std::tuple<int, float, double, char>>::type d = 0;

the error message shows

error: conversion from ‘int’ to non-scalar type
      ‘triangularize<std::tuple<int, float, double, char> >::type {aka
       std::tuple<std::function<int()>,
                  std::function<float(int)>,
                  std::function<double(int, float)>,
                  std::function<char(int, float, double)> >}’
       requested

Showing the code is correct.



来源:https://stackoverflow.com/questions/9132487/transform-tuple-to-triangular-tuple

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!