Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 24 additions & 1 deletion std/traits.d
Original file line number Diff line number Diff line change
Expand Up @@ -5620,6 +5620,13 @@ enum bool isMutable(T) = !is(T == const) && !is(T == immutable) && !is(T == inou
* Returns true if T is an instance of the template S.
*/
enum bool isInstanceOf(alias S, T) = is(T == S!Args, Args...);
/// ditto
template isInstanceOf(alias S, alias T)
{
enum impl(alias T : S!Args, Args...) = true;
enum impl(alias T) = false;
enum isInstanceOf = impl!T;
}
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would have written this as

enum bool isInstanceOf(alias S, alias T : S!Args, Args...) = true;
enum bool isInstanceOf(alias S, alias T) = false;

But: https://issues.dlang.org/show_bug.cgi?id=16403

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

noice


///
@safe unittest
Expand All @@ -5628,12 +5635,28 @@ enum bool isInstanceOf(alias S, T) = is(T == S!Args, Args...);
static struct Bar(T...) { }
static struct Doo(T) { }
static struct ABC(int x) { }
static void fun(T)() { }
template templ(T) { }

static assert(isInstanceOf!(Foo, Foo!int));
static assert(!isInstanceOf!(Foo, Bar!int));
static assert(!isInstanceOf!(Foo, int));
static assert(isInstanceOf!(Doo, Doo!int));
static assert(isInstanceOf!(ABC, ABC!1));
static assert(!__traits(compiles, isInstanceOf!(Foo, Foo)));
static assert(!isInstanceOf!(Foo, Foo));
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This might need some attention. I don't see a reason why isInstanceOf!(Foo, Foo) should fail compilation, but since this was specifically stated here, maybe there is a reason.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess it's because the original implementation did not handle things different from types as second parameter, and Foo is not a type, so it wouldn't compile.

static assert(isInstanceOf!(fun, fun!int));
static assert(isInstanceOf!(templ, templ!int));
}

@safe unittest
{
static void fun1(T)() { }
static void fun2(T)() { }
template templ1(T) { }
template templ2(T) { }

static assert(!isInstanceOf!(fun1, fun2!int));
static assert(!isInstanceOf!(templ1, templ2!int));
}

/**
Expand Down