is operator and SortedRange

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Nov 11 04:00:05 PST 2016


On Friday, November 11, 2016 11:49:25 RazvanN via Digitalmars-d-learn wrote:
> I am a bit confused about how the is operator works. I have a
> function which receives an InputRange and a predicate. Now I need
> to be able to test if the InputRange is actually a SortedRange. I
> don't care about how the datatypes behind the SortedRange or the
> predicate, I just need to see if the object is a SortedRange. I
> have tried the following test:
>
> static if(is(typeof(haystack) == SortedRange!(T, _pred), T,
> _pred))
>
> where haystack is the InputRange, but the test fails. Is there a
> way to test if the InputRange is a SortedRange without having to
> explicitly pass the primitive tupe on top of which the
> SortedRange is built?

The correct way to do this with an is expression is a bit esoteric, and you
don't want to have to deal with it. Fortunately, someone added an
appropriate trait to std.traits to do this for you: std.traits.isInstanceOf
(which should arguably be called isInstantiationOf, but it is what it is):

http://dlang.org/phobos/std_traits.html#isInstanceOf

And by the way, what you're trying to use is an "is expression," not the "is
operator." The is operator is used for doing a bitwise comparison of two
objects. e.g.

struct S
{
    int i;
}

assert(S(5) is S(5));

or

int[] arr;

assert(arr is null);

and it's a runtime constructor, not a compile time one, unlike is
expressions.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list