www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Template functions inside interface

reply Zans <lllllll mail.com> writes:
Is there any way to declare template functions inside interface 
and then override them in a class?
Trying to compile the following code results in "undefined 
reference" error:

import std.stdio;

interface MyInterface
{
     T doAndReturnSomething(T)(T param);
}

class MyClass : MyInterface
{
     override T doAndReturnSomething(T)(T param)
     {
         return param;
     }
}

void main()
{
     MyInterface myClass = new MyClass();
     writeln(myClass.doAndReturnSomething!(string)("Hello"));
}

Thanks in advance!
Aug 04 2020
parent reply Adam D. Ruppe <destructionator gmail.com> writes:
On Tuesday, 4 August 2020 at 13:36:15 UTC, Zans wrote:
 Is there any way to declare template functions inside interface 
 and then override them in a class?
No, the templates in the interface are automatically considered `final`. So the body must be in the interface too to avoid that undefined reference error. You can have them forward to normal methods in the interface though, just there needs to be a fixed number of them with concrete types.
Aug 04 2020
parent Steven Schveighoffer <schveiguy gmail.com> writes:
On 8/4/20 9:39 AM, Adam D. Ruppe wrote:
 On Tuesday, 4 August 2020 at 13:36:15 UTC, Zans wrote:
 Is there any way to declare template functions inside interface and 
 then override them in a class?
No, the templates in the interface are automatically considered `final`. So the body must be in the interface too to avoid that undefined reference error. You can have them forward to normal methods in the interface though, just there needs to be a fixed number of them with concrete types.
I was kind of surprised the compiler didn't complain about override there. Is override ever a valid attribute for a template function? Is there a reason we ignore it for templates? I can imagine a lot of confusion for something like: import std.stdio; interface MyInterface { T doAndReturnSomething(T)(T param){return T.init;} } class MyClass : MyInterface { override T doAndReturnSomething(T)(T param) { return param; } } void main() { MyInterface myClass = new MyClass(); writeln(myClass.doAndReturnSomething("Hello")); } Which compiles, runs, and prints nothing. -Steve
Aug 04 2020