使用元序列交织VT解包

Edw*_*nge 5 c++ variadic-templates

template <int I> struct int_ {};

template < typename ... Pack >
struct thingy
{
    void call()
    {
       f(???);
    }
 };
Run Code Online (Sandbox Code Playgroud)

实例化时,它最终应该是:

struct thingy<int,char,double>
{
    void call()
    {
        f(int, int_<1>(), char, int_<2>(), double, int_<3>());
    }
}
Run Code Online (Sandbox Code Playgroud)

你怎么想,可以做到吗?怎么样?

我唯一能想到的是使用N个不同的参数进行重载,如下所示:

template < typename T0 > struct thingy<T0> { ... };
template < typename T0, typename T1 > struct thingy<T0,T1> { ... };

etc...
Run Code Online (Sandbox Code Playgroud)

每个都有一个调用实现.

Mat*_* M. 5

能做到吗

当然是。

怎么样 ?

分几个步骤。

  • 您需要能够创建整数范围
  • 您需要能够交错两个序列

让我们从整数范围开始。

template <size_t...>
struct IntegralPack {};

template <size_t A, size_t... N>
IntegralPack<N..., A> push_back(IntegralPack<N...>);

template <size_t A, size_t... N>
IntegralPack<A, N...> push_front(IntegralPack<N...>);

template <size_t L, size_t H>
struct IntegralRangeImpl {
    typedef typename IntegralRangeImpl<L+1, H>::type Base;
    typedef decltype(push_front<L>((Base()))) type;
};

template <size_t X>
struct IntegralRangeImpl<X, X> {
    typedef IntegralPack<> type;
};

template <size_t L, size_t H>
struct IntegralRange {
     static_assert(L <= H, "Incorrect range");
     typedef typename IntegralRangeImpl<L, H>::type type;
};
Run Code Online (Sandbox Code Playgroud)

转换步骤非常简单(感谢):

template <typename...>
struct TypePack {};

template <size_t... N>
TypePack<int_<N>...> to_int(IntegralPack<N...>);
Run Code Online (Sandbox Code Playgroud)

因此,下一个困难是合并。

template <typename... As, typename... Bs>
TypePack<As..., Bs...> cat(TypePack<As...>, TypePack<Bs...>);

template <typename, typename> struct Interleaver;

template <>
struct Interleaver<TypePack<>, TypePack<>> {
  typedef TypePack<> type;
};

template <typename A0, typename B0, typename... As, typename... Bs>
struct Interleaver<TypePack<A0, As...>, TypePack<B0, Bs...>> {
  typedef typename Interleaver<TypePack<As...>, TypePack<Bs...>>::type Base;
  typedef decltype(cat(TypePack<A0, B0>{}, Base{})) type;
};
Run Code Online (Sandbox Code Playgroud)

放在一起:

template <typename... Pack>
struct thingy {
    typedef typename IntegralRange<1, sizeof...(Pack) + 1>::type Indexes;
    typedef decltype(to_int(Indexes{})) Ints;
    typedef typename Interleaver<TypePack<Pack...>, Ints>::type Types;

    void call() { this->callImpl(Types{}); }

    template <typename... Ts>
    void callImpl(TypePack<Ts...>) {
        f(Ts{}...);
    }
};
Run Code Online (Sandbox Code Playgroud)

多达姆!