www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Interfaces and templates

reply JN <666total wp.pl> writes:
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? If so, why doesn't it throw an error 
about unimplemented write (or incorrectly implemented) method?
Sep 20 2019
next sibling parent Adam D. Ruppe <destructionator gmail.com> writes:
On Friday, 20 September 2019 at 19:02:11 UTC, JN wrote:
 If so, why doesn't it throw an error about unimplemented write 
 (or incorrectly implemented) method?
because you never used it. templates don't get checked by the compiler until they are used...
Sep 20 2019
prev sibling parent =?UTF-8?Q?Ali_=c3=87ehreli?= <acehreli yahoo.com> writes:
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 error. 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 Ali
Sep 20 2019