c++ - std::async 与类成员函数

标签 c++ multithreading std


我是 std::async 的新手,我在理解它的工作原理时遇到了问题。我在网络上的某个地方看到了如何将成员函数传递给 std::async 的示例,但它似乎无法编译。这里有什么问题?没有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();
  }
};

最佳答案

你应该能够使用 std::bind 创建一个可调用的函数对象:

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

在您的示例中,&Test::test 不是一个采用 Test 类型参数的函数,正如 std::async 所期望的那样。相反,它是成员函数,必须以不同的方式调用。

关于c++ - std::async 与类成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48857679/

相关文章:

java - Android处理程序,不在ui线程中执行post()

c++ - std::map clear() 崩溃 - 多线程

c# - 如何在多线程应用程序中执行文件日志记录

c++ - 使用 std::bind 将函数传递给函数

c++ - 矩阵运算符重载不起作用

c# - C# 中未处理的异常与 C++ CLI Wrapper 交谈

c++ - 用于查找文件名索引的 libzip 函数不起作用 C++

c++ - QtSerialPort:在 Windows 7 上重复读取

opencv - OpenCV中复杂Mat的访问元素

c++ - 如何预分配(保留)priority_queue<vector>?