简体   繁体   English

C ++:像在Java中那样将接口作为参数传递

[英]C++: Pass interface as parameter like in Java

I want to do some stuff in C++ that i can do in Java. 我想在C ++中做一些我可以在Java中做的事情。 Here is my Java code: 这是我的Java代码:

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++. 我想用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. 一种方法是使用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;
    }
  ));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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