簡體   English   中英

C ++將函數參數傳遞給另一個lambda

[英]C++ passing function arguments to another lambda

關於我的lambda,我有一堆樣板代碼。 這是原油

目前,讓我們假設myClass看起來像這樣:

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

通過在運行時分配其lambda,如下所示:

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

我希望它看起來像:

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

這樣我就可以這樣稱呼:

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

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

我只想傳遞參數並確保它們匹配。

假設我將有不確定數量的參數和不同類型,如何將其包裝到函數中?

謝謝!

我設法解決了這個問題。 這是我的解決方案:

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

原始功能通過其他方式擴展,它從原始lambda中刪除了先前的功能。

這是示例用法:

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

應該按順序打印:

212

附加活動!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM