C ++:像Java一样将接口作为参数传递

时间:2016-02-09 00:58:45

标签: java c++ c++11 lambda interface

我想用C ++做一些我可以用Java做的东西。这是我的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!");
            }
        });
    }
}

我想用C ++做。能够在函数调用中实现接口对我来说非常重要。有可能吗?

1 个答案:

答案 0 :(得分:0)

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