简体   繁体   中英

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?

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;
    }
  ));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM