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>
}
在运行时分配的 lambdas 是这样的:
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
附加活动!
我有一堆关于我的 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>
}
在运行时分配的 lambdas 是这样的:
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
附加活动!