Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Make FutureContinuation reusable in simgrid::xbt::Task
[simgrid.git] / include / xbt / functional.hpp
index 537ba8f..1f8abfb 100644 (file)
@@ -13,6 +13,7 @@
 #include <functional>
 #include <future>
 #include <utility>
+#include <tuple>
 
 #include <xbt/sysdep.h>
 #include <xbt/utility.hpp>
@@ -153,6 +154,80 @@ constexpr auto apply(F&& f, Tuple&& t)
     >());
 }
 
+template<class T> class Task;
+
+/** Type-erased run-once task
+ *
+ *  * Like std::function but callable only once.
+ *    However, it works with move-only types.
+ *
+ *  * Like std::packaged_task<> but without the shared state.
+ */
+template<class R, class... Args>
+class Task<R(Args...)> {
+private:
+  // Type-erasure for the code:
+  class Base {
+  public:
+    virtual ~Base() {}
+    virtual R operator()(Args...) = 0;
+  };
+  template<class F>
+  class Impl : public Base {
+  public:
+    Impl(F&& code) : code_(std::move(code)) {}
+    Impl(F const& code) : code_(code) {}
+    ~Impl() override {}
+    R operator()(Args... args)
+    {
+      return code_(std::forward<Args>(args)...);
+    }
+  private:
+    F code_;
+  };
+  std::unique_ptr<Base> code_;
+public:
+  Task() {}
+  Task(std::nullptr_t) {}
+
+  template<class F>
+  Task(F&& code) :
+    code_(new Impl<F>(std::forward<F>(code))) {}
+
+  operator bool() const { return code_ != nullptr; }
+  bool operator!() const { return code_ == nullptr; }
+
+  template<class... OtherArgs>
+  R operator()(OtherArgs&&... args)
+  {
+    std::unique_ptr<Base> code = std::move(code_);
+    return (*code)(std::forward<OtherArgs>(args)...);
+  }
+};
+
+template<class F, class... Args>
+auto makeTask(F code, Args... args)
+-> Task< decltype(code(std::move(args)...))() >
+{
+  typedef decltype(code(std::move(args)...)) result_type;
+
+  class Impl {
+  private:
+    F code_;
+    std::tuple<Args...> args_;
+  public:
+    Impl(F code, std::tuple<Args...> args) :
+      code_(std::move(code)),
+      args_(std::move(args)) {}
+    result_type operator()()
+    {
+      return simgrid::xbt::apply(std::move(code_), std::move(args_));
+    }
+  };
+
+  return Impl(std::move(code), std::make_tuple(std::move(args)...));
+}
+
 }
 }