2016-11-15 159 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); 

应在顺序打印:

附加事件!

相关问题