View source code
Display the source code in std/range/primitives.d from which this page was generated on github.
Report a bug
If you spot a problem with this page, click here to create a Bugzilla issue.
Improve this page
Quickly fork, edit online, and submit a pull request for this page. Requires a signed-in GitHub account. This works well for small changes. If you'd like to make larger changes you may want to consider using local clone.

Template 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.

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 std.string.representation or std.utf.byCodeUnit.

Arguments

template hasLength(R);

Deprecation

Historically hasLength!R yielded true for types whereby R.length returns other types convertible to ulong, such as int, ushort, const(size_t), user-defined types using alias this, or notably ulong on 32-bit systems. This behavior has been deprecated. After December 2017, hasLength will yield true only if R.length yields the exact type size_t.

Example

static assert(!hasLength!(char[]));
static assert( hasLength!(int[]));
static assert( hasLength!(inout(int)[]));

struct A { ulong length; }
struct B { size_t length() { return 0; } }
struct C { @property size_t length() { return 0; } }
static assert( hasLength!(A));
static assert( hasLength!(B));
static assert( hasLength!(C));
}

/**
Returns <code class="lang-d"><span class="kwd">true</span></code> if <code class="lang-d"><span class="pln">R</span></code> is an infinite input range. An
infinite input range is an input range that has a statically-defined
enumerated member called <code class="lang-d"><a href="../../../std/range/primitives/empty.html"><span class="pln">empty</span></a></code> that is always <code class="lang-d"><span class="kwd">false</span></code>,
for example:

struct MyInfiniteRange { enum bool empty = false; ...

Authors

Andrei Alexandrescu, David Simcha, and Jonathan M Davis. Credit for some of the ideas in building this module goes to Leonardo Maffi.

License

Boost License 1.0.

Comments