是否可以输入参数包?

use*_*020 9 c++ templates variadic-templates c++11

是否可以输入参数包?例如

template<class T, class... Args>
struct A
{
    typedef T Type; // We typedef it, then its derived class can use it.
                    // How about for parameter packs?

    // Option 1:
    typedef Args Arguments;

    // Option 2:
    using Arguments = Args;

    // Option 3: I can put in a tuple, but how can I untuple it to a pack
    typedef tuple<Args...> Tuple;
};
Run Code Online (Sandbox Code Playgroud)

我想使用上述技术来实现以下功能

template<int... VALUES>
struct IntegralSequence
{
    enum { SIZE = sizeof...(VALUES) };

    template <unsigned I>
    struct At
    {
        enum { VALUE = typename tuple_element<I, 
                       tuple<integral_constant<int, VALUES>...>>::type::value
             };
    };
};

template<unsigned N>
struct AscendingSequence
{
    typedef IntegralSequence<AscendingSequence<N-1>::VALUES..., N> Type;
    using VALUES = Type::VALUES; // if it works
};

template<>
struct AscendingSequence<1>
{
    typedef IntegralSequence<0> Type;
    using VALUES = Type::VALUES; // if it works
};
Run Code Online (Sandbox Code Playgroud)

iav*_*avr 14

您可以将它们打包在一个tuple或任意空的类模板中(我更喜欢称之为pack):

template<typename... Args>
struct pack { };

template<class T, class... Args>
struct A
{
    using args = pack<Args...>;
};
Run Code Online (Sandbox Code Playgroud)

如果你在A例如函数模板中给出并且想要推断Args...,你可以这样做:

template<typename... Args, typename A>
void f(pack<Args...>, A a) { /* use Args... here */ }

template<typename A>
void f(A a) { f(typename A::args(), a); }
Run Code Online (Sandbox Code Playgroud)

pack在这种情况下,空虚很方便.否则你需要一些其他方法来传递args而不实际传递tuple包含数据(例如将其包装到另一个空结构中).

或者,在类模板专业化中:

template<typename T, typename = typename T::args>
struct B_impl;

template<typename T, typename... Args>
struct B_impl <T, pack<Args...> >
{
    // use Args... here
};

template<typename T>
using B = B_impl<T>;
Run Code Online (Sandbox Code Playgroud)

我想这些是@dyp提到的演绎和部分特化的选项.


编辑这是对编辑过的问题的回应.好的,这显然是一个XY问题.如果IntegralSequence你只需要,你可以std::make_integer_sequence在C++ 14中使用,或者在几分钟前检查我对另一个问题的回答,以便有效实施.

  • +1 用于使用元组以外的包装器类型,这完全与关注点分离有关。 (2认同)