I'm making a threadpool and I have some methods that have to take as input objects that subclass the class Task
.
I have this class:
struct Task {
virtual ~Task() = default;
virtual void run();
};
and the threadpool has a method like this:
void submit(Task val);
I would like to make jobs the threadpool has to execute by subclassing the Task class and passing these objects to the threadpool, like:
class Example : public Task {
....
void run() override {
cout << this->sayHi << endl;
....
}
}
class Example2 : public Task {
....
void run() override {
cout << this->a + this-> b << endl;
}
Example e (3);
Example2 e2 ("Hello");
tp.submit(e);
tp.submit(e2);
My problem is that if I try to make Task a pure virtual class, by writing void run() = 0
it then complains since a virtual class cannot be used as parameter for the submit
method of the threadpool.
Is there a feature like in Java where I can make a template parameter specifying that the type must subclass a given type? (eg. class C < T extends Task>
) ?
A solution could be to implement the run method of Task and making it throw an exception, but this could possibly cause problem at runtime if the Task is used by someone who's distracted, and I would prefer a way that's checked by the compiler.