www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Arguments of function as an array.

reply Jonathan <JonathanILevi gmail.com> writes:
Is there a way in D to take past arguments as an array?  A like a 
normal Variadic function.  All the arguments should be of the 
same type just as an array.

Basically I want to allow a function like this to be called 
without square brackets.

void fun(int[] intArray) {
     //...
}
void main() {
     fun([5,6,4]);
}

Like  this:

void fun(int... intArray) {
     //typeof(intArray) is `int[]`
}
void main() {
     fun(5,6,4);
}

Is this doable in D?
Apr 26 2018
next sibling parent ag0aep6g <anonymous example.com> writes:
On 04/26/2018 11:28 PM, Jonathan wrote:
 Is there a way in D to take past arguments as an array?  A like a normal 
 Variadic function.  All the arguments should be of the same type just as 
 an array.
 
 Basically I want to allow a function like this to be called without 
 square brackets.
 
 void fun(int[] intArray) {
      //...
 }
 void main() {
      fun([5,6,4]);
 }
 
 Like  this:
 
 void fun(int... intArray) {
      //typeof(intArray) is `int[]`
 }
 void main() {
      fun(5,6,4);
 }
 
 Is this doable in D?
void fun(int[] intArray ...) {} https://dlang.org/spec/function.html#typesafe_variadic_functions Note that such an array is not garbage collected. It's a slice of the stack. Don't return it from the function.
Apr 26 2018
prev sibling parent Jonathan M Davis <newsgroup.d jmdavisprog.com> writes:
On Thursday, April 26, 2018 21:28:27 Jonathan via Digitalmars-d-learn wrote:
 Is there a way in D to take past arguments as an array?  A like a
 normal Variadic function.  All the arguments should be of the
 same type just as an array.

 Basically I want to allow a function like this to be called
 without square brackets.

 void fun(int[] intArray) {
      //...
 }
 void main() {
      fun([5,6,4]);
 }

 Like  this:

 void fun(int... intArray) {
      //typeof(intArray) is `int[]`
 }
 void main() {
      fun(5,6,4);
 }

 Is this doable in D?
For better or worse, D has multiple types of variadic functions. Variadic templated functions are almost certainly the most commonly used, but what the spec calls "typesafe variadic functions" result in a dynamic array like what you're talking about: https://dlang.org/spec/function.html#typesafe_variadic_functions - Jonathan M Davis
Apr 26 2018