D issues are now tracked on GitHub. This Bugzilla instance remains as a read-only archive.
Issue 3875 - std.range.hasLength does not work if .length is defined inside a static if
Summary: std.range.hasLength does not work if .length is defined inside a static if
Status: RESOLVED INVALID
Alias: None
Product: D
Classification: Unclassified
Component: phobos (show other issues)
Version: D2
Hardware: All All
: P2 minor
Assignee: No Owner
URL:
Keywords:
Depends on:
Blocks:
 
Reported: 2010-03-04 06:11 UTC by Philippe Sigaud
Modified: 2015-06-09 01:27 UTC (History)
1 user (show)

See Also:


Attachments

Note You need to log in before you can comment on or make changes to this issue.
Description Philippe Sigaud 2010-03-04 06:11:53 UTC
std.range.hasLength does not work if the .length member is defined inside a static if. It's a common case for ranges wrapping other ranges and trying to expose their input's properties:
---
static if (hasLength!Input)
    int length() { return _input.length;}
----
for example.


Here is some code demonstrating the problem:

----
import std.range;

struct Lengthy(bool i) {
    int front() { return 1;}
    void popFront();
    static if (i)
        int length() { return 1;}
}

void main() {
    Lengthy!true i;
    Lengthy!false ni;
    assert(hasLength!(typeof(i))); // Error: AssertError. Considers i has no .length defined.
    assert(!hasLength!(typeof(ni)));
}
----

And a possible solution that seems to work quite well in practice:
----
template hasLength(R) {
    enum bool hasLength = __traits(compiles, R.length);
}
----
Comment 1 Masahiro Nakagawa 2010-05-04 17:23:19 UTC
"static if" has nothing to do with this issue. length method should be a property.