+ ~Task()
+ {
+ if (vtable_ && vtable_->destroy)
+ vtable_->destroy(code_);
+ }
+
+ Task(Task const&) = delete;
+ Task& operator=(Task const&) = delete;
+
+ Task(Task&& that)
+ {
+ std::memcpy(&code_, &that.code_, sizeof(code_));
+ vtable_ = that.vtable_;
+ that.vtable_ = nullptr;
+ }
+ Task& operator=(Task&& that)
+ {
+ if (vtable_ && vtable_->destroy)
+ vtable_->destroy(code_);
+ std::memcpy(&code_, &that.code_, sizeof(code_));
+ vtable_ = that.vtable_;
+ that.vtable_ = nullptr;
+ return *this;
+ }
+
+ template<class F,
+ typename = typename std::enable_if<bits::isUsableDirectlyInTask<F>()>::type>
+ Task(F const& code)
+ {
+ const static TaskErasureVtable vtable {
+ // Call:
+ [](TaskErasure& erasure, Args... args) -> R {
+ // We need to wrap F un a union because F might not have a default
+ // constructor: this is especially the case for lambdas.
+ union no_ctor {
+ no_ctor() {}
+ ~no_ctor() {}
+ F code ;
+ } code;
+ if (!std::is_empty<F>::value)
+ // AFAIU, this is safe as per [basic.types]:
+ std::memcpy(&code.code, &erasure.any, sizeof(code.code));
+ code.code(std::forward<Args>(args)...);
+ },
+ // Destroy:
+ nullptr
+ };
+ if (!std::is_empty<F>::value)
+ std::memcpy(&code_.any, &code, sizeof(code));
+ vtable_ = &vtable;
+ }
+
+ template<class F,
+ typename = typename std::enable_if<!bits::isUsableDirectlyInTask<F>()>::type>
+ Task(F code)
+ {
+ const static TaskErasureVtable vtable {
+ // Call:
+ [](TaskErasure& erasure, Args... args) -> R {
+ // Delete F when we go out of scope:
+ std::unique_ptr<F> code(static_cast<F*>(erasure.ptr));
+ (*code)(std::forward<Args>(args)...);
+ },
+ // Destroy:
+ [](TaskErasure& erasure) {
+ F* code = static_cast<F*>(erasure.ptr);
+ delete code;
+ }
+ };
+ code_.ptr = new F(std::move(code));
+ vtable_ = &vtable;
+ }