0

I'm just making the jump from Java to C++. I'm fairly confident with C++ now, and I was trying to make a template class. Does C++ have a way to guarantee that the template argument extends a certain class? In Java, I can use class MyClass<? extends AnotherClass>. If not, is there a way around this limitation?

Thanks!

user207421
  • 305,947
  • 44
  • 307
  • 483

1 Answers1

5

You can static_assert(std::is_base_of<Base, T>::value, "Argument must extend base!");.

However, note that relative to doing this in Java, in C++ this is nearly totally worthless. There's practically no use case that actually needs it.

Puppy
  • 144,682
  • 38
  • 256
  • 465
  • Alright, I'm trying to make an EventListener class and enforce that T extends Event. Should I use this statement in the ctor? – Defenestrator Nov 26 '14 at 22:15
  • 3
    If you really need to enforce that T derives from Event. But like I said, that constraint is virtually worthless in C++. If you want to enforce it, it's time to step back and rethink. – Puppy Nov 26 '14 at 22:16
  • Alright, thanks. I'll accept this as soon as it lets me. – Defenestrator Nov 26 '14 at 22:22
  • 1
    Be aware that C++ templates are far more powerful beasts than .Net generics, which are slightly more powerful than Java ones. Specifically, they are instantiated at *compile-time* by substituting the *actual template-arguments* you used, *before compiling them*. – Deduplicator Nov 26 '14 at 22:23
  • Handy to know, thanks. – Defenestrator Nov 26 '14 at 22:28