Proper way to accept either static or dynamic array as a parameter
H. S. Teoh
hsteoh at quickfur.ath.cx
Sun Sep 12 01:48:07 UTC 2021
On Sun, Sep 12, 2021 at 01:08:17AM +0000, Alex Bryan via Digitalmars-d-learn wrote:
> I am having trouble discovering what the proper (or at least a proper)
> way is to write a function that can take either a static or dynamic
> array as a parameter. My current implementation consists of 2
> overloaded functions (one takes a dynamic array, the other takes a
> static array) with 99% copy/pasted code. My intuition tells me this is
> dirty, and there's a better way to do this with templates, but for the
> life of me I just can't figure it out. Would someone be so kind as to
> please help me out?
[...]
Just make the function take an array parameter. Static arrays will decay
into a slice (though my recommendation is to explicitly slice it with
the [] operator):
auto myFunction(T[] data) { ... }
T[10] staticArr;
T[] dynArr = [ ... ];
myFunction(staticArr); // implicit slice, not recommended
myFunction(staticArr[]); // explicit slice, better
myFunction(dynArr);
T
--
Life is too short to run proprietary software. -- Bdale Garbee
More information about the Digitalmars-d-learn
mailing list