[英]Forwarding a function to std::thread via a lambda expression
我正在阅读此处的注释以了解示例异步函数实现。
试图编译下面的代码
#include <future>
#include <iostream>
#include <thread>
#include <chrono>
#include <ctime>
#include <type_traits>
int f(int x) {
auto start = std::chrono::system_clock::now();
std::time_t start_time = std::chrono::system_clock::to_time_t(start);
std::cout << "returning " << x << " at " << std::ctime(&start_time) << std::endl;
return x;
}
template<typename Function, typename... Args>
auto async(Function&& function, Args&&... args) {
std::promise<typename std::result_of<Function(Args...)>::type> outer_promise;
auto future = outer_promise.get_future();
auto lambda = [function, promise = std::move(outer_promise)](Args&&... args) mutable {
try {
promise.set_value(function(args...));
} catch (...) {
promise.set_exception(std::current_exception());
}
};
std::thread t0(std::move(lambda), std::forward<Args>(args)...);
t0.detach();
return future;
}
int main() {
auto result1 = async(f, 1);
auto result2 = async(f, 2);
}
我收到以下编译器错误,我很难理解。
我想要一些关于为什么根据编译器没有正确声明这个function
arg 的指导。
In instantiation of 'async(Function&&, Args&& ...)::<lambda(Args&& ...)> mutable [with Function = int (&)(int); Args = {int}]':
22:61: required from 'struct async(Function&&, Args&& ...) [with Function = int (&)(int); Args = {int}]::<lambda(int&&)>'
28:3: required from 'auto async(Function&&, Args&& ...) [with Function = int (&)(int); Args = {int}]'
37:27: required from here
22:88: error: variable 'function' has function type
22:88: error: variable 'function' has function type
In instantiation of 'struct async(Function&&, Args&& ...) [with Function = int (&)(int); Args = {int}]::<lambda(int&&)>':
28:3: required from 'auto async(Function&&, Args&& ...) [with Function = int (&)(int); Args = {int}]'
37:27: required from here
22:18: error: field 'async(Function&&, Args&& ...) [with Function = int (&)(int); Args = {int}]::<lambda(int&&)>::<function capture>' invalidly declared function type
要获得result_of
结果类型,您必须访问type
:
std::promise< typename std::result_of<Function(Args...)>::type > outer_promise;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.