2016-11-15 162 views
0

我有一堆關於我的lambdas的樣板代碼。這裏是一個原油C++將函數參數傳遞給另一個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){}); 

我只是想沿着參數傳遞,並確保它們匹配。

如何將其包含到一個函數中,假設我將有一個未定義數目的參數和不同類型?

謝謝!

+0

'eventList'是一個'map'嗎?它的類型是什麼? – Arunmu

+0

啊是壞的例子我會編輯。我正在使用運行時定義的lambdas類,如std :: function OnClick – Avalon

+0

仍然不清楚。什麼是'事件'?連接到事件的lambda是否總是帶3個參數,只有內部函數簽名發生變化? – Arunmu

回答

0

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

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

應在順序打印:

附加事件!

相關問題