As we probably have to wait a bit until std::future::then
is implemented I'm trying currently to write a very simple task wrapper the problem is calling the callback function. Lets say we have a class like:
template<typename... ARG>
class Task
{
public:
typedef std::function<void(ARG...)> task_func_t;
Task() {}
void then(task_func_t callback) { this->callback_ = callback; }
void finish(ARG... arguments)
{
this->callback_(std::forward<ARG>(arguments)...);
}
void operator()(ARG... arguments)
{
this->callback_(std::forward<ARG>(arguments)...);
}
private:
task_func_t callback_;
};
and lets assume the following usage:
std::shared_ptr<Task<int>> sum(int n1, int n2)
{
auto ptr = std::make_shared<Task<int>>();
myPool.process([n1, n2, ptr]
{
(*ptr.get())(n1 + n2);
}
return ptr;
}
void test()
{
sum(5, 6)->then([](int sum) { std::cout << "Sum is " << sum << std::endl };
}
I sometimes have the problem the callback is called before the function is actually set. I know I could check as long as the callback is invalid but I don't really like this solution so are there other smart solutions? I actually thought about doing it like this:
return task.before(do prepare work);
.then(process result)
So then It would call the the create thread when linking is done in then. The perfect solution would be something which calls then
before as requirement but I think Its actually impossible as long I want this design.