samedi 1 avril 2023

How to use Pimpl to achieve template base class with virtual functions in C++17?

I am trying to write different implementations of a ThreadPool. To make it neat for testing, I would like to provide a base interface to be implemented by each implementation. I searched online and get notified that virtual and template cannot be mixed together. People suggests me to try Pimpl design pattern to achieve this. But I am relatively new to design pattern and not sure how to achieve this. Could someone help a bit?

Here is the interface I wish could be achieved. (It's not compile-able)

// threadpool.h

class BasePoolInterface {
 public:
  // not able to compile, my ideal scenario.
  template <typename F, typename... Args>
  virtual decltype(auto) SubmitTask(F &&new_task, Args &&...args) = 0;
};

class SomePoolImplementation: public BasePoolInterface {
public:
  template <typename F, typename... Args>
  decltype(auto) SubmitTask(F &&new_task, Args &&...args) {
    // ... real implementation
  }
};

I roughly know Pimpl is about making the implementation into another class, and let the main class contains to pointer to the Implementation class, so that we separate the "client-facing interface" and real implemenation. But I am not sure how that can help with the virtual and template. Thanks in advance!

Aucun commentaire:

Enregistrer un commentaire