Enum member std.range.primitives.hasLength
Yields true
if R
has a length
member that returns a value of size_t
type. R
does not have to be a range. If R
is a range, algorithms in the
standard library are only guaranteed to support length
with type size_t
.
enum hasLength(R)
= is(Length == size_t) && !(isAutodecodableString!R && !isAggregateType!R);
Note that length
is an optional primitive as no range must implement it. Some
ranges do not store their length explicitly, some cannot compute it without
actually exhausting the range (e.g. socket streams), and some other ranges may
be infinite.
Although narrow string types (char[]
, wchar[]
, and their qualified
derivatives) do define a length
property, hasLength
yields false
for them.
This is because a narrow string's length does not reflect the number of
characters, but instead the number of encoding units, and as such is not useful
with range-oriented algorithms. To use strings as random-access ranges with
length, use representation
or byCodeUnit
.
Example
static assert(!hasLength!(char[]));
static assert( hasLength!(int[]));
static assert( hasLength!(inout(int)[]));
struct A { size_t length() { return 0; } }
struct B { @property size_t length() { return 0; } }
static assert( hasLength!(A));
static assert( hasLength!(B));
Authors
Andrei Alexandrescu, David Simcha, and Jonathan M Davis. Credit for some of the ideas in building this module goes to Leonardo Maffi.