繁体   English   中英

如何将此std :: function传递给std :: async

[英]How can I pass this std::function to std::async

我正在处理一段多线程代码,但似乎无法将std :: function对象传递给std :: async函数。 我确定我做错了什么,但我不知道那会是什么。 因此,我准备了这段代码,以便也许有人认识可以帮助我。

Test1演示此std :: function对象起作用。
Test2包含我想要执行的操作; 只有我将函数对象包装到lambda中。
Test3包含我不知道的示例。

std::function<void(AsyncFunctionExample&)> current_function;

void Test1() {
  current_function = &AsyncFunctionExample::Function1;
  while(current_function != nullptr)
    current_function(*this);
}

void Test2() {
  current_function = &AsyncFunctionExample::Function1;
  while(current_function != nullptr)
    const std::future<void> function_future = std::async([&](){current_function(*this);});
}

void Test3() {
  current_function = &AsyncFunctionExample::Function1;
  while(current_function != nullptr)
    const std::future<void> function_future = std::async(current_function, *this);
}

此示例的完整代码可以在此处找到。 Stackoverflow编辑器警告说,不允许我转储完整的代码文件,所以这就是为什么在这里将其简化为基本内容的原因。

我收到的编译器错误是:
没有匹配的函数可以调用'async(std :: function&,AsyncFunctionExample&)'const std :: future function_future = std :: async(current_function,* this);

这对我没有多大帮助。 它基本上向我说明,没有与我的呼叫匹配的签名。 但是我无法从该错误中找出呼叫的哪一部分是错误的,并且我不知道如何更改它才能正常工作。

您不能通过std::async传递引用,因为它需要复制值。 您可以使用std::ref修复此问题:

const std::future<void> function_future = std::async(current_function, std::ref(*this));

或者,只需将功能更改为:

std::function<void(AsyncFunctionExample*)> current_function;

然后,您可以直接传递this

const std::future<void> function_future = std::async(current_function, this);

暂无
暂无

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

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