Type inference and overloaded functions

Kenji Hara k.hara.pg at gmail.com
Thu Dec 12 20:12:48 PST 2013


On Thursday, 12 December 2013 at 18:20:25 UTC, bearophile wrote:
> 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);
> }

There's a known issue that the function foo takes the slice of 
stack allocated data. Today some peoples argue that it is unsafe 
operation and should be disallowed in @safe code.

> 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

I'm afraid that allowing foo([4, 5, 6]s) would easily cause 
memory corruption. I don't want to hurt language future by the 
trivial syntactic sugar.

Kenji Hara


More information about the Digitalmars-d-learn mailing list