| |
| Posted by Mike Parker in reply to Adel Mamin | PermalinkReply |
|
Mike Parker
Posted in reply to Adel Mamin
| On Wednesday, 29 July 2015 at 20:20:47 UTC, Adel Mamin wrote:
> Hello,
>
> Why dmd cannot inference the type of 'arr' in my_func() parameter?
> test.d:
>
> import std.stdio;
>
> void my_func(auto arr)
> {
> writeln(arr);
> }
>
> void main()
> {
> auto arr = new int[5];
>
> arr = [1, 2, 3, 4, 5];
>
> my_func(arr);
> }
>
>> dmd test.d
> test.d(3): Error: undefined identifier arr
Consider what would happen if my_func is compiled in a library. How would the compiler know what type arr is if there is no code around that is calling it? In that case, it would be unable to compile the function. Furthermore, what happens if my_func is called with multiple types? A function has one instance and one instance only, so arr can only ever be one type.
With templates, the code is always available, so the compiler can always know what the type is inside the function. And you can have multiple instances of any template, so it's possible for arr to be different types.
|