提取类的模板参数并迭代它们的最紧凑方法是什么?

Fab*_*bio 6 c++ templates variadic-templates c++11 c++14

在下面的小程序中,我展示了我目前用于提取类的模板参数并通过递归辅助函数迭代它的解决方案.

我想知道是否有更简洁的方法来做,正如我在下面的评论中的伪代码中解释的那样.

template <int...Is> struct Pack {};

template <int I> struct B
{
    static void foo() { std::cout << I << "\n"; }
};

// recursive helper function, also used to extract the parameter pack arguments
template <int I, int...Is>
void foo_helper( Pack<I, Is...>&& )
{
    B<I>::foo();
    foo_helper( Pack<Is...>{} );
}

// terminate recursion
void foo_helper( Pack<>&& ) {}

struct A
{
    typedef Pack<1,3,5> ints;

    static void foo()
    {
        // this is what I do
        foo_helper(ints{});

        // this is what I would like to do, ideally in one single line
        // 1) extract the template arguments pack from ints, without creating an helper function for that
        // 2) iterate on the template arguments of the pack without a recursive helper
        // In pseudocode, something like:
        // (B<IterateOver<ArgumentsOf<ints>>>::foo());
    }
};

int main()
{
    A::foo();
}
Run Code Online (Sandbox Code Playgroud)

Rum*_*rak 1

这是我能想到的最短的:

#include <iostream>

template<int... Is>
struct Pack;

template <int I> struct B
{
    static void foo() { std::cout << I << "\n"; }
};

template<typename PACK> struct unpack;

template<int...Is>
struct unpack<Pack<Is...>>
{ 
  template<template<int> class T>
  static void call()
  { 
    using swallow = int[sizeof...(Is)];
    (void) swallow{(T<Is>::foo(), 0)...};
  }
};

struct A
{
    typedef Pack<1,3,5> ints;

    static void foo()
    {
      unpack<ints>::call<B>();
    }
};

int main()
{
    A::foo();
}
Run Code Online (Sandbox Code Playgroud)