Type inference and overloaded functions

bearophile bearophileHUGS at lycos.com
Thu Dec 12 10:20:24 PST 2013


Namespace:

> Your gig: 
> https://github.com/D-Programming-Language/dmd/pull/2952#discussion_r8288045

This is part of the thread there:

>> Furhtermore, what if we indeed want to pass a dynamic array ?<<

Kenji> Use cast. In real world, if overloaded function takes both 
int[] and int[3], normally int[3] version would provide 
specialized implementation for 3 length arrays (eg. unroll the 
loop to operate each elements of the given array). Therefore 
force to invoke int[] version with array literal is not usual 
situation. Cast will fit in such case.<


If I have a function foo that takes a slice as input, and I want 
to pass it two arrays, the first time allocated on the heap and 
the second on the stack, I have to use an auxiliary variable:


void foo(int[]) {}
void main() {
     foo([1, 2, 3]);
     int[3] tmp = [4, 5, 6];
     foo(tmp);
}


DMD generates:

__Dmain comdat
L0:     push    EBX
         mov EAX,offset FLAT:_D11TypeInfo_Ai6__initZ
         push    3
         push    EAX
         call    near ptr __d_arrayliteralTX
         mov EBX,EAX
         mov dword ptr [EAX],1
         xor EAX,EAX
         mov dword ptr 4[EBX],2
         mov dword ptr 8[EBX],3
         add ESP,8
         pop EBX
         ret


With the []s syntax it should become:


void foo(int[]) {}
void main() {
     foo([1, 2, 3]);
     foo([4, 5, 6]s);
}


But I don't know how much common is such need.

In the Rust language when you write an array literal you always 
prefix it with a symbol, to tell the compiler where you want to 
allocate it. So I think it's not so useless :-)

Bye,
bearophile


More information about the Digitalmars-d-learn mailing list