c++ scalable grouping of lambda functions in blocks of an arbitrary number

夙愿已清 提交于 2019-12-12 23:05:36

问题


I have to execute several lambda functions, but every each N lambdas a prologue() function also must be run. The number of lambdas can be arbitrary large and N is known at compile time. Something like this:

static void prologue( void )
{
    cout << "Prologue" << endl;
}

int main()
{
    run<3>( // N = 3
        [](){ cout << "Simple lambda func 1" << endl; },
        [](){ cout << "Simple lambda func 2" << endl; },
        [](){ cout << "Simple lambda func 3" << endl; },
        [](){ cout << "Simple lambda func 4" << endl; },
        [](){ cout << "Simple lambda func 5" << endl; },
        [](){ cout << "Simple lambda func 6" << endl; },
        [](){ cout << "Simple lambda func 7" << endl; }
    );
}

outputs:

Prologue
Simple lambda func 1
Simple lambda func 2
Simple lambda func 3
Prologue
Simple lambda func 4
Simple lambda func 5
Simple lambda func 6
Prologue
Simple lambda func 7
End

Remainders must be handled properly.

I have reached the following solution, but as you can see it is not very scalable because I have to write a handler for each N!

It is possible to do some magic meta-programming to cover every possible N? Have I lost the focus and there is a completely different approach to solve this problem? Everything must be resolved at compile time.

#include <iostream>    
using namespace std;

static void prologue( void );

// Primary template
template< int N, typename... Args>
struct Impl;

// Specialitzation for last cases
template< int N, typename... Args >
struct Impl
{
    static void wrapper( Args... funcs )
    {
        Impl<N-1, Args...>::wrapper( funcs... );
    }
};

// Specilitzation for final case
template<int N>
struct Impl<N>
{
    static void wrapper( )
    {
        cout << "End" << endl;
    }
};

template< typename Arg1, typename... Args >
struct Impl<1, Arg1, Args...>
{
    static void wrapper( Arg1 func1, Args... funcs )
    {
        prologue();
        func1();

        Impl<1, Args...>::wrapper( funcs... );
    }
};

template< typename Arg1, typename Arg2, typename... Args >
struct Impl<2, Arg1, Arg2, Args...>
{
    static void wrapper( Arg1 func1, Arg2 func2, Args... funcs )
    {
        prologue();
        func1();
        func2();

        Impl<2, Args...>::wrapper( funcs... );
    }
};

template< typename Arg1, typename Arg2, typename Arg3, typename... Args >
struct Impl<3, Arg1, Arg2, Arg3, Args...>
{
    static void wrapper( Arg1 func1, Arg2 func2, Arg3 func3, Args... funcs )
    {
        prologue();
        func1();
        func2();
        func3();

        Impl<3, Args...>::wrapper( funcs... );
    }
};

// Static class implementation wrapper
template< int N, typename... Args >
static void run( Args... funcs )
{
    Impl<N, Args...>::wrapper( funcs... );
}

EDIT: posted a related question.


回答1:


A simpler solution

template <std::size_t N, typename ... Ts>
void run (Ts const & ... fn)
 {
   using unused = int[];

   std::size_t  i { N-1U };

   (void)unused { 0, ( (++i % N ? 0 : (prologue(), 0)), (void)fn(), 0)... };
 }

--EDIT-- added (void) in front to the call of fn() to avoid the comma-hijack trick explained by Yakk in a comment (thanks!).




回答2:


What about using a helper struct?

template <std::size_t N, std::size_t M>
struct runH
 {
   template <typename T0, typename ... Ts>
   static void func (T0 const & f0, Ts const & ... fn)
    {
      f0();
      runH<N, M-1U>::func(fn...);
    }

   static void func ()
    { }
 };

template <std::size_t N>
struct runH<N, 0>
 {
   template <typename ... Ts>
   static void func (Ts const & ... fn)
    {
      if ( sizeof...(fn) )
         prologue();

      runH<N, N>::func(fn...);
    }
 };

template <std::size_t N, typename ... Ts>
void run (Ts const & ... fn)
 { runH<N, 0>::func(fn...); }



回答3:


Preable:

Takes a function object. Returns a function object that takes many args, passing them one at a time to the first object.

template<class F>
void foreach_arg(F&&f){
  return [f=std::forward<F>(f)](auto&&...args){
    using discard=int[];
    (void)discard{0,(0,void(
      f(decltype(args)(args))
    ))...}
  };
}

Then we just keep track of the index:

template<std::size_t N, class...Args>
void run(Args&&...args){
  std::size_t i = 0;
  foreach_arg([&](auto&&arg){
      if (!(i%N))prologue();
      ++i;
      arg();
    }
  )( args... );
}

A more complex solution. It calculates the index as a constexpr value.

First, get nth arg from a pack:

template<std::size_t N, class...Args>
decltype(auto) nth(Args&&...args){
  return std::get<N>(std::forward_as_tuple(std::forward<Args>(args)...));
}

Takes an index sequence. Returns a function that takes a function object, then passes that object compile-time indexes:

template<std::size_t...Is>
auto index_over(std::index_sequence<Is...>){
  return [](auto&&f)->decltype(auto){
    return decltype(f)(f)(std::imtegral_constant<std::size_t,Is>{}...);
  };
}

Lets you invoke above 0...N-1, which is the common case:

template<std::size_t N>
auto index_upto(std::integral_constant<std::size_t,N> ={}){
  return index_over(std::make_index_sequence<N>{});
}

Now, actual problem specific code:

template<std::size_t N, class...Args>
void run(Args&&...args){
  index_upto<sizeof...(Args)>()(
    foreach_arg([&](auto I){
      if (!(I%N))prologue();
      nth<I>(std::forward<Args>(args)...)(); 
    })
  );
}

there are probably tpyos.

This one may also compile slower; it generates O(n^2) code.



来源:https://stackoverflow.com/questions/44750040/c-scalable-grouping-of-lambda-functions-in-blocks-of-an-arbitrary-number

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!