Reply to dsimcha,

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.

Having this distinction could be a problem because it might make it hard to tell if a function is or is not virtual and also would make tweaking the list in a base class risky.

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.


I think you are right in that it would be easy to implement because I think you could reduce it to an alias declaration. OTOH I think you would get most of what you are proposing with some sugar around alias.


Reply via email to