Search code examples
c++functionlambdaboilerplatetype-deduction

C++ passing function arguments to another lambda


I have a bunch of boilerplate code in regards to my lambdas. here is an crude

For the moment lets assume that myClass looks like this:

class myClass
{
   public:
    std::function<void(int,int)> event;
    std::function<void(std::string)> otherEvent;
    <many more std::function's with different types>
}

With its lambdas assigned during runtime as such:

myClass->event =[](T something,T something2,T something3)
{
    yetAnotherFunction(something,something,something3);
    //do something else.
} 

How I want it to look like:

void attachFunction(T& source, T yetAnotherFunction)
{
    source = [](...)
    {
       yetAnotherFunction(...);
       //do something else.
    }
}

so that I can call something like this:

attachFunction(myClass->event,[](int a,int b){});

and

attachFunction(myClass->otherEvent,[](std::string something){});

I simply want to pass along the parameters and make sure that they match.

How do I wrap this into a function, Assuming that I will have an undefined number of parameters and different types?

Thanks!


Solution

  • I have managed to solve this. This is my solution:

    template <typename R, typename... Args>
    void attachEvent(std::function<R(Args...)>& original,std::function<R(Args...)> additional)
    {
        original = [additional](Args... args)
        {
            additional(args...);
            std::cout << "Attached event!" << std::endl;
        };
    }
    

    The original function is extended by additional, it erases previous functionality from original lambda.

    Here is example usage:

      std::function<void(float,float,float)> fn = [](float a ,float b,float c){};
      std::function<void(float,float,float)> additional = [](float a,float b,float c){std::cout << a << b << c << std::endl;};
    
      attachEvent(fn,additional);
      fn(2.0f,1.0f,2.0f);
    

    Which should print in sequence:

    212

    Attached Event!