www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Type inference of a function parameter

reply "Adel Mamin" <adel mm.st> writes:
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
Jul 29 2015
next sibling parent "anonymous" <anonymous example.com> writes:
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); } ----
Jul 29 2015
prev sibling parent "Mike Parker" <aldacron gmail.com> writes:
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.
Jul 29 2015