Templates and virtual functions
Walter Bright
newshound1 at digitalmars.com
Wed Jan 21 17:38:42 PST 2009
dsimcha wrote:
> Every once in a while, it comes up on this NG that a significant limitation of
> templates is that they can't add virtual functions to classes. Of course,
> removing this limitation for the general case is impossible w/o completely
> changing the compilation model in ways that are bad ideas for other reasons.
> However, would it be reasonable to allow _specific instantiations_ of
> templates to add virtual functions? This might be a nice convenience feature.
Setting aside the technical issues for the moment, I'd like to go back
to the notion that structs are for compile time polymorphism and classes
are for runtime polymorphism. Template functions are clearly in the
compile time camp, and if you need compile time polymorphism in a class,
perhaps the design should be seriously looked at to see if that's
justifiable.
As to resolving the technical issue, put the instantiation of the
template inside another virtual function:
class foo {
T nothing(T)(T arg) { // Non-virtual.
return arg;
}
int virtual_nothing(int arg)
{
return nothing!(arg);
}
float virtual_nothing(float arg)
{
return nothing!(arg);
}
}
The advantage of this is there is nothing new to learn.
More information about the Digitalmars-d
mailing list