是否可以输入参数包?

时间:2014-04-09 16:10:29

标签: c++ templates c++11 variadic-templates

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

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;
};

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

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
};

1 个答案:

答案 0 :(得分:14)

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

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

template<class T, class... Args>
struct A
{
    using args = pack<Args...>;
};

如果您获得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); }
在这种情况下,

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>;

我想这些是@dyp提到的演绎和部分专业化的选项。


编辑这是对已编辑问题的回应。好的,这显然是一个XY问题。如果您需要IntegralSequence,则可以在C ++ 14中使用std::make_integer_sequence或在几分钟前检查my answer to another question以实现高效实施。

相关问题