Thread overview
Type inference of a function parameter
Jul 29, 2015
Adel Mamin
Jul 29, 2015
anonymous
Jul 30, 2015
Mike Parker
July 29, 2015
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

Adel
July 29, 2015
On Wednesday, 29 July 2015 at 20:20:47 UTC, Adel Mamin wrote:
> void my_func(auto arr)
> {
>   writeln(arr);
> }

There are no `auto` parameters in D. You have to make it a template explicitly:

----
void my_func(A)(A arr)
{
  writeln(arr);
}
----

July 30, 2015
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.