Create tasks from C++ lambdas

This is a convenience function that you can use to create an AsyncTask from any callable - including a C++11 lambda. This avoids the boilerplate of creating AsyncTask subclasses. It will be part of 1.11, but in the meantime, you can copy this directly into your project (consider it public domain).

template<class Callable>
AsyncTask *make_task(Callable callable, const std::string &name, int sort = 0, int priority = 0) {
  class InlineTask final : public AsyncTask {
  public:
    InlineTask(Callable callable, const std::string &name, int sort, int priority) :
      AsyncTask(name),
      _callable(std::move(callable)) {
      _sort = sort;
      _priority = priority;
    }

    ALLOC_DELETED_CHAIN(InlineTask);

  private:
    virtual DoneStatus do_task() override final {
      return _callable(this);
    }

    Callable _callable;
  };
  return new InlineTask(std::move(callable), name, sort, priority);
}

Example for usage:

framework.get_task_mgr().add(make_task([=](AsyncTask *task) -> AsyncTask::DoneStatus {
  //do whatever here
  return AsyncTask::DS_cont;
}, "test task"));
3 Likes