digitalmars.D.learn - Interfaces and templates
- JN (17/17) Sep 20 2019 import std.stdio;
- Adam D. Ruppe (3/5) Sep 20 2019 because you never used it. templates don't get checked by the
- =?UTF-8?Q?Ali_=c3=87ehreli?= (18/36) Sep 20 2019 No. Function templates cannot be virtual functions. There are at least
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
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
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 tableIf 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