On Monday, 25 July 2016 at 12:37:18 UTC, Bahman Movaqar wrote:
Suppose I have the following function:

    public auto max(alias comp, Range)(Range r)
    in {
      assert(r !is null && !r.empty);
    }
    body {
      // ...
    }

When the function after a series of chained `map` operations, I get the following error:

    Error: incompatible types for ((r) !is (null)):
'MapResult!(__lambda2, SInvoiceLine[])' and 'typeof(null)'

Of course if I remove `r !is null` from the `in` block, everything will work. But I'm curious; how can I check for a `null` in this case?

In the general case, the vast majority of ranges you work with will be value types. In the rare case where it's a reference type, you can use static if to specialize the assert. Two possibilities have already been suggested in this thread, but given that ranges are nearly always going to be a struct or a class, then you might do this inside the template:

static if(is(Range == class)) { // check for null }

You may also want to add a constraint:

import std.range : isInputRange;
public auto max(alias comp, Range)(Range r) if(isInputRange!Range) {
   static if(is(Range == class)) assert(r !is null && !r.empty);
   else assert(!r.empty);
}



Reply via email to