On Thursday, May 14, 2015 02:47:22 rcorre via Digitalmars-d-learn wrote: > I've run into this situation a lot: > I have a function that returns a range (in this case, a slice of > a custom container). > In some cases, the function needs to return an empty range. > > It sounded like takeNone was what I wanted: > > @nogc auto fun() { > return (some_condition) ? getRange() : getRange.takeNone; > } > > but there is a return type ambiguity. I finally ended up doing > this: > > @nogc auto fun() { > return (some_condition) ? getRange().take(size_t.max) : > getRange.takeNone; > } > > I'm not sure if this is clever or insane. > It works, but just looks a bit crazy to me. > Does anyone else run into this situation? Have any cool ways to > solve it? > MyRange is an inputRange, and I can't use a wrapper (InputRange) > and keep the @nogc.
takeNone is as close as you can get in O(1) in the general case, because there's no well-defined way to get an empty range from a range other than to keep calling popFront on it until it's empty (which would be O(n)). So, takeNone gives you an empty range of the same type if it can, and if it can't then the best that it can do is to use takeExactly with 0. It looks like what you're trying to do is to force the return type to be Take!R in all cases (or the original type if that's what Take!R is able to alias itself to). I don't know if that will work in all cases or not, but I don't see how you have much choice. The only way that you could keep the original range type in all cases would be if we had a standard way to make a range empty that takeNone could use, and we don't. - Jonathan M Davis