【问题标题】:C++ passing function arguments to another lambdaC++ 将函数参数传递给另一个 lambda
【发布时间】:2016-11-15 04:54:30
【问题描述】:

我有一堆关于我的 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){});

我只是想传递参数并确保它们匹配。

如果我将有未定义数量的参数和不同类型,我如何将其包装到一个函数中?

谢谢!

【问题讨论】:

  • eventListmap 吗?它的类型是什么?
  • 啊是的坏例子我会编辑。我正在使用具有运行时定义的 lambda 的类,例如 std::function OnClick
  • 还是不清楚。 event 是什么?附加到事件的 lambda 是否总是采用 3 个参数并且只有内部函数签名发生变化?
  • No 参数个数未知。它可以是一个或三个或更多。参数的数量及其类型发生了哪些变化。
  • 我编辑并添加了一个类的示例。

标签: c++ function lambda boilerplate type-deduction


【解决方案1】:

我已经设法解决了这个问题。这是我的解决方案:

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

附加事件!

【讨论】:

    猜你喜欢
    • 2012-09-25
    • 2020-10-03
    • 1970-01-01
    • 1970-01-01
    • 2014-01-06
    • 2019-10-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多