I was wondering if there could be any way to write a template function in an abstract class, and have it (the template function) automatically instantiated with the type of the derived class?
So you have a class that looks something like this
class A
{
virtual template < typename T>
void vtfunc(void)
};
class B : public A
{
/// No declared members pertainin开发者_如何学Pythong to this example
}
Then, whenever a class derived from A is declared, it compiles "vtfunc" with itself as the template parameter T. Then, calling vtfunc() through an interface of A calls the isntance of that function compiled for its derived class B.
Is there any way of doing this, or writing something fiddley that have this effect?
Obviously I am aware that the template parameter could only affect the internals of the class, and not the return type and parameters - they would need to be the same because of the way polymorphism works.
I’m not sure what you’re after but one common pattern is the so-called curiously recurring template pattern; here, the base class itself is the template, not its member functions. In other words:
template <typename T>
class A
{
virtual void vtfunc(void)
};
class B : public A<B>
{
…
};
Consider using a non-member function instead.
精彩评论