Interfaces and templates

Ali Çehreli acehreli at
Fri Sep 20 19:51:23 UTC 2019

On 09/20/2019 12:02 PM, JN wrote:
 > import std.stdio;
 > interface IWriter
 > {
 >      void write(U)(U x);
 > }
 > class Foo : IWriter
 > {
 >      void write(U)(U x, int y)
 >      {
 >          writeln(x);
 >      }
 > }
 > void main()
 > {
 > }
 > Does this code make sense?

No. Function templates cannot be virtual functions. There are at least 
two reasons that I can think of:

1) Function templates are not functions but their templates; only their 
instances would be functions

2) Related to that, languages like D that use virtual function pointer 
tables for dynamic dispatch cannot know how large that table should be; 
so, they cannot compile for an infinite number of entries in that table

 > If so, why doesn't it throw an error about
 > unimplemented write (or incorrectly implemented) method?

Foo.write hides IWriter.write (see "name hiding"). Name hiding is not an 

When you call write on the Foo interface it takes two parameters:

   auto i = new Foo();
   i.write(1, 2);    // Compiles

When you call write on the IWriter interface it takes one parameter but 
there is no definition for it so you get a linker error:

   IWriter i = new Foo();
   i.write(1);    // LINKER ERROR


More information about the Digitalmars-d-learn mailing list