Created
May 14, 2015 12:39
-
-
Save rcorre/7a62395c53baf3c0bfbc to your computer and use it in GitHub Desktop.
maybeEmptyRange
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import std.stdio; | |
/* | |
* Copy-paste from std.range. | |
* Comment this and uncomment `import std.range`, and the static assert will fail. | |
*/ | |
template isInputRange(R) | |
{ | |
enum bool isInputRange = is(typeof( | |
(inout int = 0) | |
{ | |
R r = R.init; // can define a range object | |
if (r.empty) {} // can test for empty | |
r.popFront(); // can invoke popFront() | |
auto h = r.front; // can get the front of the range | |
})); | |
} | |
//import std.range; | |
struct MyRange { | |
void popFront() { } | |
@property int front() { return 0; } | |
@property bool empty() { return false; } | |
} | |
struct MaybeEmpty(R) if (isInputRange!R) { | |
private bool _isEmpty; | |
private R _input; | |
alias _input this; | |
this(bool isEmpty, R input) { | |
_input = input; | |
_isEmpty = isEmpty; | |
} | |
@property bool empty() { | |
return _isEmpty || _input.empty; | |
} | |
} | |
auto maybeEmpty(R)(bool empty, R input = R.init) if (isInputRange!R) { | |
return MaybeEmpty!R(empty, input); | |
} | |
auto foo(bool b) { | |
return b ? maybeEmpty!MyRange(true) : maybeEmpty!MyRange(false, MyRange()); | |
} | |
unittest { | |
auto a = maybeEmpty!MyRange(true); | |
alias R = typeof(a); | |
static assert(isInputRange!MyRange); | |
static assert(isInputRange!R); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment