Can templated functions be used in interfaces?

Jakob Ovrum jakobovrum at gmail.com
Thu Jul 11 05:12:33 PDT 2013


On Thursday, 11 July 2013 at 12:00:20 UTC, Gary Willoughby wrote:
> Also i've noticed that the compiler doesn't complain if 
> templated functions are not implemented in the classes that 
> implement the interface, which is wrong!

What you've done is declared a non-virtual member of the 
interface without a definition. This is, in itself, completely 
fine:

/* myinterface.di */

interface Foo
{
     void bar(); // virtual member; implemented in derived classes

     final void foo(); // Declaration without definition, as this 
is a D interface module (equivalent of a C or C++ header file)
}

/* myinterface.d */

interface Foo
{
     void bar(); // virtual member; implemented in derived classes

     final void foo()
     {
         // Defines 'Foo.foo'
     }
}

The above example displays useful behaviour and is thus allowed, 
but with templated functions, the declaration and definition may 
not be separated in this way, so it only makes sense for 
non-templated functions.

If you try to link an executable using code that uses the 
definition-less declarations (D interface module), *without 
providing the linker with code that implements (defines) those 
declarations*, you will get a linker error like the one you did. 
What you did was instantiate a function template without a 
definition then trying to link an executable without that code, 
giving you the error. It doesn't actually make any sense to try 
to separate templated function declarations from their 
definitions, so the code should be refused at compile-time.


More information about the Digitalmars-d-learn mailing list