jeudi 4 avril 2019

What is the right way to implement interface forwarding from one to many in C++?

I have a class that calls back via an interface IFoo. This class sits within a library that I cannot change. I would like to be able to register multiple receivers with that interface IFoo.

I can do this by creating a new class FooProxy that implements IFoo and in every method in IFoo, I would then call all of the registered IFoo interfaces.

class IFoo {
public:
  virtual void Bar(int x) = 0;
};
class FooProxy : public IFoo {
public:
  void Bar(int x) override {
     for (auto foo : registered_foo_) {
        foo->Bar(x);
     }
  }
  void RegisterFoo(IFoo* foo) { registered_foo_.push_back(foo); }
private:
  list<IFoo> registered_foo_;
};

The problem with this is that I have to write every method in IFoo again inside FooProxy.

Is there a quick way to templatize this? What if I want to create a thread pool to forward using a different thread so that the caller of Bar(.) won't get blocked?

Aucun commentaire:

Enregistrer un commentaire