Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a template extend a class in a C++ function?

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++?

like image 205
gkovalechyn Avatar asked Mar 24 '23 04:03

gkovalechyn


1 Answers

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.

like image 149
chris Avatar answered Apr 02 '23 11:04

chris