What's wrong with D's templates?
S
S at S.com
Mon Dec 21 13:17:43 PST 2009
On 2009-12-18 17:07:57 -0800, bearophile <bearophileHUGS at lycos.com> said:
> Yigal Chripun:
>
>> .Net generics for example work by creating an instantiation for each
>> value type (same as c++ templates) and one instantiation for all
>> reference types since at the binary level all reference types are simply
>> addresses. C++ can't do this since it has no separation between
>> "structs" and "classes".
>> there is no casting involved since the full type info is stored.
>> so a Foo<Bar> will be typed as Foo<Bar> at the binary level as well and
>> you can use APIs to query this at runtime.
>
> In D structs and classes are distinct enough, but they currently
> produce duplicated templated code, this may be fixed:
>
> void foo(T)(T o) {
> printf("foo: %d\n", o.y);
> }
>
> class A { int x = 1; }
> class B : A { int y = 2; }
> class C : A { int y = 3; }
>
> void main() {
> B b = new B();
> C c = new C();
> foo(b);
> foo(c);
> }
>
> /*
> DMD1:
>
> _D4temp17__T3fooTC4temp1BZ3fooFC4temp1BZv comdat
> push EAX
> mov ECX,offset FLAT:_D4temp1C6__vtblZ[018h]
> push dword ptr 0Ch[EAX]
> push ECX
> call near ptr _printf
> add ESP,8
> pop EAX
> ret
>
> _D4temp17__T3fooTC4temp1CZ3fooFC4temp1CZv comdat
> push EAX
> mov ECX,offset FLAT:_D4temp1C6__vtblZ[018h]
> push dword ptr 0Ch[EAX]
> push ECX
> call near ptr _printf
> add ESP,8
> pop EAX
> ret
>
>
> LDC:
>
> _D13testtemplates27__T3fooTC13testtemplates1BZ3fooFC13testtemplates1BZv:
> subl $12, %esp
> movl 12(%eax), %eax
> movl %eax, 4(%esp)
> movl $.str3, (%esp)
> call printf
> addl $12, %esp
> ret
>
> _D13testtemplates27__T3fooTC13testtemplates1CZ3fooFC13testtemplates1CZv:
> subl $12, %esp
> movl 12(%eax), %eax
> movl %eax, 4(%esp)
> movl $.str3, (%esp)
> call printf
> addl $12, %esp
> ret
> */
>
> Bye,
> bearophile
This isn't a bug. This is how it is template code is supposed to
work. However, there does seem to be one problem in the output you're
giving.
LDC should not be producing different name mangling than DMD! This is
part of the D ABI last I checked, so as to avoid all the problems C++
has associated with libraries from different compilers not playing nice.
-S
More information about the Digitalmars-d
mailing list