How do you safely deal with range.front?
aliak
something at something.com
Mon Jan 1 18:25:11 UTC 2018
On Monday, 1 January 2018 at 04:18:29 UTC, Ali Çehreli wrote:
> If you're fine with specifying the function as a template
> argument, the following works. (As seen with 's => s.foo()'
> below, you have to use a lambda for member functions anyway.)
>
> Ali
Nice! Thanks :) And I think your usage for something named
"ifFront" actually makes more sense than using it to return
"saferef" functionality.
I've basically implemented an optional type for now and the
"iffront" implementation looks like this:
import std.range: isInputRange;
auto iffront(Range)(Range r) if (isInputRange!Range) {
import std.range: ElementType, empty, front;
import optional: no, some;
return r.empty ? no!(ElementType!Range) : some(r.front);
}
unittest {
import std.algorithm: filter;
assert([false].filter!"a".iffront.empty); // because optional
is a range
}
unittest {
import std.algorithm: filter;
import optional: some, none;
struct A {
int f() {
return 7;
}
}
assert([A()].filter!"false".iffront.f == none);
assert([A()].filter!"true".iffront.f == some(7));
}
And thanks everyone for the input. I'll play around with some of
the ideas and see what comes of it.
More information about the Digitalmars-d-learn
mailing list