Can You Expand Arrays into an Argument List?

H. S. Teoh hsteoh at quickfur.ath.cx
Fri May 15 19:19:59 UTC 2020


On Fri, May 15, 2020 at 06:44:52PM +0000, surlymoor via Digitalmars-d-learn wrote:
[...]
> I don't often miss JS, but one particular feature that I enjoyed is
> the ability to expand arrays into argument lists using a unary
> operator.
> 
> Example: add(...[1, 1]) === add(1, 1) // IIRC
> 
> I've been looking in Phobos and the spec, but nothing's popped out to
> me. Is there a fairly obvious alternative to this, or am I going to
> have to experiment with some templates and mixins? (Not that I mind,
> btw, D's metaprogramming is very fun.)
[...]

It's possible to do it, but the called function has to support it. If
that's not an option, then you're out of luck and probably have to use
metaprogramming instead.  Here's how to do it:

	int add(int[] args...) {
		... // access `args` here as an array
	}

	void main() {
		int[] arr = [ 1, 2, 3 ];
		add(arr);
		add(1, 2);
		add(1, 3, 4, 5, 7);
	}


T

-- 
Recently, our IT department hired a bug-fix engineer. He used to work for Volkswagen.


More information about the Digitalmars-d-learn mailing list