Runnable implementation using packaged_task in c++11

347 views Asked by At

I am trying to create a Runnable interface in c++11 using packaged_task, with child class overriding run() function. I don't know why this code is not compiling. Its giving error related to type argument.

/usr/include/c++/4.8.1/functional:1697:61: error: no type named ‘type’ in ‘class std::result_of()>’ typedef typename result_of<_Callable(_Args...)>::type result_type;

Below is my code snippet. Could someone plz give me some information on this error and whether implementing Runnable this way is a right way to proceed ?

class Runnable {

  public:
  explicit Runnable() {
    task_ = std::packaged_task<int()>(&Runnable::run);
    result_ = task_.get_future();
    std::cout << "starting task" << std::endl;
  }

  virtual int run() = 0;

  int getResult() {
    task_();
    return result_.get();
  }

  virtual ~Runnable() {
    std::cout << "~Runnable()" << std::endl;
  }

  private:
  std::future<int>  result_;
  std::packaged_task<int()> task_;

};

class foo : public Runnable {

  int fib(int n) {
    if (n < 3) return 1;
    else return fib(n-1) + fib(n-2);
  }

  public:
  explicit foo(int n) : n_(n) {}
  int run() {
    cout << "in foo run() " << endl;
    int res = fib(n_);
    cout << "done foo run(), res = " << res << endl;
    return res;
  }
  ~foo() {}

  private:
  int n_;
};

int main(int argc, char*argv[]) {
  stringstream oss;
  oss << argv[1];
  int n;
  oss >> n;
  shared_ptr<foo> obj(new foo(n));
  obj->run();
  cout << "done main" << endl;
  return 0;
}
0

There are 0 answers