I have a function that has a template class as a parameter:
template<class T> void scheduleTask(T* a);
But I want the class who called this function to extend the class "Runnnable", in Java you can do this by:
public <T extends Runnable> void scheduleTask(T a);
If I can, how would I do this in c++?
You have the possibility of enforcing this restriction with std::is_base_of
. You have two options of how you use it.
Affect overload resolution with SFINAE:
template<typename T, typename = typename std::enable_if<std::is_base_of<Runnable, T>::value, T>::type>
void scheduleTask(T *a) {...}
Cleaner, gives a nice error message, but does not affect overload resolution:
template<typename T>
void scheduleTask(T *a) {
static_assert(std::is_base_of<Runnable, T>::value, "T must be derived from Runnable");
...
}
Both of these require C++11. I know Boost has a couple tricks surrounding this up its sleeve if you don't have access to C++11.
That said, as Jerry says in the comments, it might make more sense to not use a template at all. If you look into the matter and are still sure you need one, this should work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With