简体   繁体   English

std::async 与类成员函数

[英]std::async with class member function


I'm kind of new to std::async and I have problems understanding how it works.我对std::async有点std::async ,我在理解它是如何工作的方面遇到了问题。 I saw example of how to pass member funcion to std::async somewhere on the web but it seems not to compile.我看到了如何将成员函数传递给网络上某处的std::async示例,但它似乎无法编译。 Whats the problem here?这里有什么问题? How can it be done without lambda?没有 lambda 怎么办?

class Test {
  std::future<void> f;
  void test() {}
  void runTest() {
    // ERROR no instance overloaded matches argument list
    f = std::async(std::launch::async, &Test::test, this); 

    // OK...
    f = std::async(std::launch::async, [this] {test();}); 
  }
  void testRes() {
    f.get();
  }
};

You should be able to use std::bind to create a callable function object:您应该能够使用 std::bind 创建一个可调用的函数对象:

f = std::async(std::launch::async, std::bind(&Test::test, this));

In your example &Test::test is not a function that takes one parameter of type Test , as it would be expected by std::async .在您的示例中, &Test::test 不是一个采用Test类型参数的函数,正如std::async所期望的那样。 Instead it is member function, which must be called differently.相反,它是成员函数,必须以不同的方式调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM