digitalmars.D.learn - Type inference of a function parameter
- Adel Mamin (16/17) Jul 29 2015 Hello,
- anonymous (9/13) Jul 29 2015 There are no `auto` parameters in D. You have to make it a
- Mike Parker (11/28) Jul 29 2015 Consider what would happen if my_func is compiled in a library.
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.dtest.d(3): Error: undefined identifier arr Adel
Jul 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); } ----
Jul 29 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); }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.dmd test.dtest.d(3): Error: undefined identifier arr
Jul 29 2015