Overriding Template Methods

Ali Çehreli acehreli at yahoo.com
Sun Jan 29 18:43:39 PST 2012


On 01/29/2012 06:23 PM, Daniel L. Alves wrote:
 > Hi,
 > I don't know if this is a bug or if I'm doing something wrong, but 
I'm not
 > being able to override template methods. This can be seen with this 
simple code:
 >
 > class Base
 > {
 >      void writeValueType( T )( T value )
 >      {
 >          writefln( "This is Base.writeValueType: value %s has type 
%s", value,
 > typeid( value ) );
 >      }
 > }
 >
 > class Derived : Base
 > {
 >      override void writeValueType( T )( T value )
 >      {
 >          writefln( "This is Derived.writeValueType: value %s has type 
%s",
 > value, typeid( value ) );
 >      }
 > }
 >
 > void main()
 > {
 >      Base b = new Derived();
 >      b.writeValueType( true );
 > }
 >
 > The output should be:
 >
 > This is Derived.writeValueType: value true has type bool
 >
 > But, instead, it is:
 >
 > This is Base.writeValueType: value true has type bool
 >
 > Am I missing something?

Template member functions cannot be virtual.

One quick reason why this is so is that Derived.writeValueType would 
have to be instantiated by the compiler, for every possible type in the 
program. This would lead to almost infinitely large virtual function 
pointer table.

I don't know whether the compiler could refuse the code to compile with 
that 'override' keyword, but luckily the code is rejected as soon as you 
add the following two lines:

     Derived d = new Derived();
     d.writeValueType(true);

Only then the compiler sees the problem:

Error: function deneme.Derived.writeValueType!(bool).writeValueType 
cannot override a non-virtual function

And that kind of makes sense, because the templates are compiled only if 
they are used and only for the types that they are used with.

Ali



More information about the Digitalmars-d-learn mailing list