繁体   English   中英

从可变参数模板调用函子

[英]Call functor from variadic template

是否可以编写可变参数模板类

template<typename Functor, int... D>
struct Foo
{
    void bar()
    {
        // ???
    }
};

相当于

template<typename Functor, int D0>
struct Foo<Functor, D0>
{
    void bar()
    {
        Functor f;
        double d0[D0];
        f(d0);
    }
};

template<typename Functor, int D0, int D1>
struct Foo<Functor, D0, D1>
{
    void bar()
    {
        Functor f;
        double d0[D0];
        double d1[D1];
        f(d0, d1);
    }
};

// And so on...

也就是说,传递给函子的参数数量等于模板参数的数量。 参数应在堆栈上分配。

通过std::tuple在堆栈上跟随参数的版本:

// Helper class to be able to use expansion of std::get<Index>(tuple)
template <int... Is> struct index_sequence {};

// Following create index_sequence<0, 1, 2, .., sizeof...(Is) - 1>
template <int Index, int... Is>
struct make_index_sequence { // recursively build a sequence of indices
    typedef typename make_index_sequence<Index - 1, Index -1, Is...>::type type;
};

template <int... Is>
struct make_index_sequence<0, Is...> { // stop the recursion when 0 is reached
    typedef index_sequence<Is...> type;
};

template<typename Functor, int... Ds>
struct Foo
{
    void bar()
    {
        bar(typename make_index_sequence<sizeof...(Ds)>::type());
    }
private:
    template <int... Is>
    void bar(index_sequence<Is...>)
    {
        Functor f;
        std::tuple<double[Ds]...> t; // std::tuple<doudle[D0], double[D1], ..>
        f(std::get<Is>(t)...);       // f(std::get<0>(t), std::get<1>(t), ..);
    }
};

那是你要的吗?

template<typename Functor, int... D>
struct Foo
{
    template<std::size_t N>
    std::array<double, N> create()
    {
       return std::array<double, N>();
    }

    void bar()
    {
       Functor f;
       f(create<D>()...);
    }
};

也许这可行:

template <typename Functor, int i, int... others>
struct Foo
{
  template <typename ...T>
  void bar(T ... rest)
  {
    double d[i];
    Foo<Functor, others...> foo;
    foo.bar(rest..., d);
  }
};

template <typename Functor, int i>
struct Foo<Functor, i>
{
  template <typename ...T>
  void bar(T ... rest)
  {
    double d[i];
    Functor f;
    f(d, rest...);
  }
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM