+ Task(Task&& that) noexcept
+ {
+ if (that.vtable_ && that.vtable_->move)
+ that.vtable_->move(buffer_, that.buffer_);
+ else
+ std::memcpy(&buffer_, &that.buffer_, sizeof(buffer_));
+ vtable_ = std::move(that.vtable_);
+ that.vtable_ = nullptr;
+ }
+ Task& operator=(Task const& that) = delete;
+ Task& operator=(Task&& that) noexcept
+ {
+ this->clear();
+ if (that.vtable_ && that.vtable_->move)
+ that.vtable_->move(buffer_, that.buffer_);
+ else
+ std::memcpy(&buffer_, &that.buffer_, sizeof(buffer_));
+ vtable_ = std::move(that.vtable_);
+ that.vtable_ = nullptr;
+ return *this;
+ }
+
+private:
+ template <class F> typename std::enable_if_t<canSBO<F>()> init(F task_code)
+ {
+ const static TaskVtable vtable {
+ // Call:
+ [](TaskUnion& buffer, Args... args) {
+ auto* src = reinterpret_cast<F*>(&buffer);
+ F code = std::move(*src);
+ src->~F();
+ // NOTE: std::forward<Args>(args)... is correct.
+ return code(std::forward<Args>(args)...);
+ },
+ // Destroy:
+ std::is_trivially_destructible<F>::value ?
+ static_cast<destroy_function>(nullptr) :
+ [](TaskUnion& buffer) {
+ auto* code = reinterpret_cast<F*>(&buffer);
+ code->~F();
+ },
+ // Move:
+ [](TaskUnion& dst, TaskUnion& src) {
+ auto* src_code = reinterpret_cast<F*>(&src);
+ auto* dst_code = reinterpret_cast<F*>(&dst);
+ new(dst_code) F(std::move(*src_code));
+ src_code->~F();
+ }
+ };
+ new (&buffer_) F(std::move(task_code));
+ vtable_ = &vtable;
+ }
+
+ template <class F> typename std::enable_if_t<not canSBO<F>()> init(F task_code)
+ {
+ const static TaskVtable vtable {
+ // Call:
+ [](TaskUnion& buffer, Args... args) {
+ // Delete F when we go out of scope:
+ std::unique_ptr<F> code(*reinterpret_cast<F**>(&buffer));
+ // NOTE: std::forward<Args>(args)... is correct.
+ return (*code)(std::forward<Args>(args)...);
+ },
+ // Destroy:
+ [](TaskUnion& buffer) {
+ F* code = *reinterpret_cast<F**>(&buffer);
+ delete code;
+ },
+ // Move:
+ nullptr
+ };
+ *reinterpret_cast<F**>(&buffer_) = new F(std::move(task_code));
+ vtable_ = &vtable;
+ }