Niobium_x February 2016

C++: Pass interface as parameter like in Java

I want to do some stuff in C++ that i can do in Java. Here is my Java code:

interface Worker
{
    public void work();
}

class Employer
{
    public void askForWork(Worker worker)
    {
        worker.work();
    }
}

public class Main
{
    public static void main(String[] args)
    {
        Employer employer = new Employer();
        employer.askForWork(new Worker()
        {
            @Override
            public void work()
            {
                System.out.println("I'm working!");
            }
        });
        employer.askForWork(new Worker()
        {
            @Override
            public void work()
            {
                System.out.println("I'm working too!");
            }
        });
    }
}

And I want to do it in C++. It is very important for me to be able to implement interface inside function call. Is it possible?

Answers


Ryo Kawaguchi February 2016

One way to do it is use std::function.

class Worker {
 public:
  explicit Worker(std::function<void()> task)
      : task_(task) {}

  void Work() {
    task_();
  }

 private:
  std::function<void()> task_;
};

class Employer {
  ...

  void AskForWork(std::unique_ptr<Worker> worker) {
    worker->Work();
  }
};

int main(...) {
  Employer employer;
  employer.AskForWork(new Worker(
    []() {
      std::cout << "I'm working!" << std::endl;
    }
  ));
}

Post Status

Asked in February 2016
Viewed 2,090 times
Voted 5
Answered 1 times

Search




Leave an answer