Templates and virtual functions

Jason House jason.james.house at gmail.com
Wed Jan 21 15:54:39 PST 2009


Robert Fraser Wrote:

> 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.
> >  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.
> 
> If you're asking what I think ytou're asking; it's already there: mixins
> 
> class foo {
>       T nothing(T)(T arg) {  // Non-virtual.
>           return arg;
>       }
> 
>       mixin nothing!(int);    // Add nothing!(int) to foo's vtable.
>       mixin nothing!(float);  // Add nothing!(float) to foo's vtable.
>   }
> 
> You can override, whatever with them. You can't use the template syntax 
> to do an override, but... I'm not sure how much of a limitation this is.

That feels like a loophole to me. What about using template syntax to call the function? I'm going to guess it'll bypass the vtable! this mix also created a lot of shadowing problems both when making calls and inheriting 



More information about the Digitalmars-d mailing list