Template method in interfaces
Lodovico Giaretta via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Wed Aug 10 08:25:40 PDT 2016
On Wednesday, 10 August 2016 at 15:20:37 UTC, Arafel wrote:
> I'm not sure if the following is even expected to work, since
> I'm not sure how the vtable for the interface would look like
> (well, that would be applicable to any overriden templated
> method, though):
>
> ---
> public interface I {
> void func(T)(T t);
> }
>
> public class C : I {
> void func(T)(T t) {
> }
> }
>
> void main() {
> I i = new C();
> i.func(1);
> }
> ---
>
> But since the error I get is in the linker, and not in the
> compiler, I guess that's somehow a bug? Or how should it work
> then?
>
> https://dpaste.dzfl.pl/7a14fa074673
>
> /d31/f76.o: In function `_Dmain':
> /d31/f76.d:(.text._Dmain+0x24): undefined reference to
> `_D3f761I11__T4funcTiZ4funcMFiZv' collect2: error: ld returned
> 1 exit status --- errorlevel 1
>
> PS: Now I see [1] that it shouldn't, so perhaps the compiler
> should reject templated methods in interfaces from the
> beginning?
>
> [1]: http://forum.dlang.org/post/jg504s$1f7t$1@digitalmars.com
Because templated functions cannot be virtual, it follows that
I.func is final. Having no body, the compiler thinks that its
body will be found by the linker in another object file, but this
does not happen, so the linker complains.
Being I.func final, C.func just hides it, so you would not incur
any problem if you called func explicitly on an object of type C.
So what you found is not a bug, but some unintuitive behaviour
due to templated functions being implicitly final and forward
declarations. Maybe the compiler should emit a warning about
implicitly-final functions in interfaces.
More information about the Digitalmars-d-learn
mailing list