[英]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.