【问题标题】:Is it possible to typedef a parameter pack?是否可以 typedef 参数包?
【发布时间】:2014-05-22 23:42:16
【问题描述】:

是否可以 typedef 参数包?例如

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

【问题讨论】:

  • “我可以放入一个元组,但我怎样才能将它解开成一个包” 使用偏特化、演绎或索引技巧。
  • 你可以使用Args... args;
  • 如果你可以粗略地描述用例,即你想在哪里解压它们,那么构建一个工作示例可能会更容易。 (@dyp 给出了三种可能性,但它们都适用于一组有限的用例)

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


【解决方案1】:

您可以将它们打包在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 提到的演绎和偏特化选项。


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

【讨论】:

  • +1 用于使用元组以外的包装器类型,这完全是关于关注点分离。
  • 只想自己实现make_integer_sequence,弹出这个问题。
  • @user1899020 我不相信!这看起来像一个 X-ABCDEF-Y 问题:-)
  • 作为一个自行车棚,我喜欢打电话给packtypes:描述它的内容,而不是它的来源。 Plus 类型不是唯一的参数包。
  • @Yakk 真。不幸的是,在我的项目中,我有一个名为types命名空间,所有元编程都在其中进行:-)
猜你喜欢
  • 2012-06-09
  • 2018-07-25
  • 1970-01-01
  • 1970-01-01
  • 2022-01-02
  • 2019-02-06
  • 2020-08-12
  • 1970-01-01
  • 2011-03-17
相关资源
最近更新 更多