【问题标题】:How to write lambda function with arguments? c++如何编写带参数的 lambda 函数? C++
【发布时间】:2014-10-21 14:48:03
【问题描述】:

我想调用一个方法(对于这个例子 std::thread 构造函数) 使用 lambda 函数,传递 int 值:

int a=10;

std::thread _testThread = thread([a](int _a){
  //do stuff using a or _a ?
});
_testThread.detach();

我不知道如何正确编写这样的函数,我得到这个错误: C2064: term 不计算为采用 0 个参数的函数

【问题讨论】:

  • 您必须像捕获a 一样捕获_a。
  • 好吧,我只需要那个线程内的'a'。
  • 这是一个 lambda 函数
  • 为什么会有一个叫_a的参数?

标签: c++ argument-passing stdthread inline-functions


【解决方案1】:

std::thread 接受一个可调用对象以及传递给它的任何参数。如果您不提供参数,std::thread 将尝试不带参数调用该对象,因此会出现错误。

如果需要参数:

std::thread _testThread{[a](int _a) {
    std::cout << a << ' ' << _a; //prints main's a, followed by somethingThatWillBe_a
}, somethingThatWillBe_a};

如果你只是想使用main的a,它已经被捕获了:

std::thread _testThread{[a] {
    std::cout << a; //prints main's a
}};

如果您认为需要分离线程,我还建议您格外小心。如果有任何加入线程的可能性,那就去吧。

【讨论】:

    【解决方案2】:

    您可以通过以下两种方式之一访问int a。要么将它作为参数传递给线程的构造函数,要么在 lambda 的闭包中捕获它:

    int a=10;
    
    // pass in a as a parameter
    std::thread _testThread1([](int _a){
    
      //do stuff using a or _a ?
    
    }, a); // pass a to the parameter _a
    _testThread1.detach();
    
    // capture a in the closure
    std::thread _testThread2([a](){ // capture a
    
      //do stuff using a or _a ?
    
    });
    _testThread2.detach();
    

    【讨论】:

      【解决方案3】:

      如果您只想将一些值传递给 lambda 函数,请查看下面的代码:

      int main()
      {
          int a = 10;
      
          [](int arg)
          {
              cout << "arg = " << arg << endl;
          }
          (a);
      
          return 0;
      }
      

      如果您想使用 lambda 函数创建线程并向其传递一些参数,请参见下一个代码示例:

      int main()
      {
          int a = 10;
      
          thread thd([](int arg) { cout << "arg = " << arg << endl; }, a);
      
          thd.join();
      
          return 0;
      }
      

      【讨论】:

        猜你喜欢
        • 2020-01-31
        • 2018-08-03
        • 2013-04-02
        • 2015-02-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多