我正在尝试使用 promises 将 packaged_task 实现为模板类。
我的编译错误说我引用了一个已删除的函数。我怀疑我需要实现复制和/或移动语义,但我很困惑如何以及从哪里开始。非常感谢任何建议:
#include "stdafx.h"
#include <iostream>
#include <future>
#include <functional>
#include <thread>
using namespace std;
//Base case
template<class>
class promised_task;
//Templated class
template<class Ret, class...Args>
class promised_task<Ret(Args...)> {
public:
//Constructor
//Takes a function argument that is forwarded to fn member
template<class F>
explicit promised_task(F&& f) :fn(f){}
//get_future member function:
future<Ret> get_future(){
return prom.get_future();
}
//Set value
void operator()(Args&&...args){
prom.set_value(fn(forward<Args>(args)...));
}
private:
//Promise member
promise<Ret> prom;
//Function member
function<Ret(Args...)> fn;
};
//Sample function from cplusplus.com
int countdown(int from, int to){
for (int i = from; i != to; --i){
cout << i << endl;
this_thread::sleep_for(chrono::seconds(1));
}
cout << "Lift off!" << endl;
return from - to;
}
//Verification function also from cplusplus.com
int main(){
promised_task<int(int, int)>tsk(countdown);
future<int>ret = tsk.get_future();
thread th(move(tsk), 10, 0);
int value = ret.get();
cout << "The countdown lasted for " << value << " seconds." << endl;
th.join();
cout << "Press any key to continue:" << endl;
cin.ignore();
return 0;
}