lundi 26 juin 2017

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

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

Aucun commentaire:

Enregistrer un commentaire