I've been looking for a workaround to the problem of type-erasing a std::packaged_task
using std::function
.
What I wanted to do was something like this:
#include <future>
#include <functional>
#include <iostream>
namespace {
std::function<void()> task;
std::future<int> make(int val) {
auto test = std::packaged_task<int()>([val](){
return val;
});
auto fut = test.get_future();
task = std::move(test);
return fut;
}
}
int main() {
auto fut = make(100);
task();
std::cout << fut.get() << "\n";
}
it's succinct and avoids re-implementing a lot of mechanics myself. Unfortunately that isn't actually legal because std::packaged_task
is move-only not copy constructable.
As a workaround I came up with the following, which implements things in terms of std::promise
and a std::shared_ptr
instead:
#include <future>
#include <functional>
#include <iostream>
namespace {
std::function<void()> task;
std::future<int> make(int val) {
auto test = std::make_shared<std::promise<int>>();
task = [test,val]() {
test->set_value(val);
test.reset(); // This is important
};
return test->get_future();
}
}
int main() {
auto fut = make(100);
task();
std::cout << fut.get() << "\n";
}
This "works for me", but is this actually correct code? Is there a nicer way to achieve the same net result?
(Note that the lifespan of the std::shared_ptr
in the second example is important for my real code. Clearly as-is I will be taking steps to prevent calling the same std::function
twice).
Aucun commentaire:
Enregistrer un commentaire