static array is no range?
cym13 via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sat Sep 5 17:25:09 PDT 2015
On Saturday, 5 September 2015 at 11:12:17 UTC, Sebastiaan Koppe
wrote:
> ```
> import std.algorithm;
> char[1024] buffer;
> buffer.find("LOCATION: "); // get error about how all the
> different versions of find don't match
> ```
>
> ```
> import std.algorithm;
> char[1024] buffer;
> buffer[0..$].find("LOCATION: "); // works as expected
> ```
You can do instead:
buffer[].find("LOCATION: ");
> Before trying the slice I manually pragma(msg) all the template
> constraints to see why it was failing. Apparently a static
> array is not a ForwardRange. Now, there is probably a good
> reason for that, that is not what I want to discuss.
>
> The point is that it is rather hard to find out what went wrong.
>
> What I would like the compiler to emit is this: `Error: buffer
> is not a ForwardRange`. But I know that wouldn't be so easy.
>
> At least the compiler shouldn't show me candidates with
> non-matching arguments length (e.g.
> `std.algorithm.searching.find(alias pred,
> InputRange)(InputRange haystack) if (isInputRange!InputRange)`)
Yes, static arrays aren't ranges. The main reason is that static
arrays are value type (ie: you copy them arround when passing
them to functions which usually has a huge cost) where ranges are
reference type (no copy, lighter, not always better as it makes
optimisation more complicated).
The standard library is designed arround ranges to make sure that
you are not copying 1024-bytes long structures arround by
accident: you'd have to do that explicitely. As a consequence,
you must generally slice arrays when passing them to phobos
functions (not always true but a good rule of thumb).
That said, if you want to benefit from array-specific
optimisations such as loop-unrolling you are generally better of
using a good old foreach and implementing the logic yourself.
Yes, it is sad, I agree.
More information about the Digitalmars-d-learn
mailing list