Thread overview
Interfaces and templates
Sep 20, 2019
JN
Sep 20, 2019
Adam D. Ruppe
Sep 20, 2019
Ali Çehreli
September 20, 2019
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?
September 20, 2019
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...
September 20, 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 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