4

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

gkovalechyn
  • 117
  • 1
  • 9
  • possible duplicate: http://stackoverflow.com/q/2631585/951890 – Vaughn Cato Jul 15 '13 at 04:02
  • 5
    You want what *called* it to extend (presumably you mean "derive from") runnable, or you want instantiated over something that's derived from? If so, you're probably making a mistake, trying to write Java in C++. The basic point of a template is to allow instantiation over anything that meets its requirements. If you want something derived from "Runanble", pass a "Runanble *" or "Runnable &", and don't use a template at all. – Jerry Coffin Jul 15 '13 at 04:03
  • Thanks, I had forgot that I could use that instead of a template. – gkovalechyn Jul 15 '13 at 16:43

1 Answers1

7

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.

chris
  • 60,560
  • 13
  • 143
  • 205