Templates and virtual functions
dsimcha
dsimcha at yahoo.com
Wed Jan 21 12:41:19 PST 2009
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.
Below is an illustration.
class foo {
T nothing(T)(T arg) { // Non-virtual.
return arg;
}
virtual nothing!(int); // Add nothing!(int) to foo's vtable.
virtual nothing!(float); // Add nothing!(float) to foo's vtable.
}
class bar : foo {
// float, int instantiations override those of foo.
// Any others are non-virtual and don't override those of foo.
T nothing(T)(T arg) {
return 2 * arg;
}
}
class baz : foo {
int nothing(int arg) { // overrides foo.nothing!(int)
return 3 * arg;
}
float nothing(float arg) { // overrides foo.nothing!(float)
return 3 * arg;
}
}
Using the virtual keyword, one could add specific instantiations of a template
to a class's vtable. Then, these functions would automatically work just like
non-template virtual functions. My guess (I'm not an expert on compiler
internals) is that this would be easy to implement, yet would help in a lot of
cases where only a few instantiations even make sense. Of course, the
compiler would throw an error when two instantiations differed only by return
type, just as with non-template functions.
More information about the Digitalmars-d
mailing list