Returning an empty range of a given type

Steven Schveighoffer via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu May 14 11:44:58 PDT 2015


On 5/13/15 10:58 PM, rcorre wrote:
> Actually, this doesn't even seem to work with a custom range:
>
> import std.range;
> import std.stdio;
> import std.algorithm;
>
>      struct MyContainer {
>        @nogc auto opSlice() {
>          struct Range {
>            @property bool empty() { return true; }
>            @property int front() { return 9; }
>            void popFront() { }
>          }
>
>          return Range();
>        }
>      }
>
>      /// Return a slice of aa[key], or an empty slice if not found
>      @nogc auto maybeGetRange(MyContainer[string] aa, string key) {
>        alias RangeType = typeof(MyContainer.init[]);
>        auto val = key in aa;
>        return (val is null) ? takeNone!RangeType :
> (*val)[].take(size_t.max);
>      }
>
> Is there any way to create an empty MyContainer.Range() without creating
> a new container?

It depends on the guts of MyContainer.Range.

I'm assuming MyContainer.Range has SOME sort of references (i.e. 
pointers) to the data in the container, so why not just have:

bool empty() { return someRef == null || yourCurrentTest; }

-Steve


More information about the Digitalmars-d-learn mailing list