Once before, I was certain that you couldn\'t do this, but the other day I was playing around with some code and it seemed to compile and work. I just want to verify that I
Think about what a template class is -- it is not a class itself, but a template the compiler can use to create classes.
As such, there's no reason you can't include a virtual function (pure or otherwise) in the template class definition, because that, in and of itself, does not generate any code, including the virtual table.
When we actually instantiate the template class, e.g. DataSource<int>
, then the compiler only needs to build the virtual table for that one selected type, so it's not any different than a (pure or otherwise) virtual function for a non-templated class.
Are virtual (pure and/or normal) virtual functions allowed within a tempate class?
Yes. Perfectly legal.
A Class template with virtual functions are absolutely fine. But, template functions with virtual keyword prefixed with in a class or template class is not allowed. Below would help you get that:
//This is perfectly fine.
template <type T>
class myClass{
virtual void function() = 0;
};
//This is NOT OK...
template<type T>
class myClass{
template <type T>
virtual void function() = 0;
};
A class template can indeed contain virtual or pure virtual functions. This was employed by Andrei Alexandresu in "Modern C++ Design" to implement the visitor pattern using templates and type lists. You can see the code here in his Loki library if you're interested.
With most standard C++ implementations, this is fine, because when the template is instantiated the virtual function ends up being one single function. Consequently, the number of slots needed in the vtable can be known within the translation unit, so a vtable can be generated.
As you mentioned, you cannot have a virtual template member function because the number of vtable slots wouldn't be known within the translation unit.
Hope this helps!