Pattern matching is-expressions

Dennis dkorpel at
Wed Aug 19 13:03:59 UTC 2020

On Wednesday, 19 August 2020 at 07:29:18 UTC, Stefan Koch wrote:
> At least in my opinion this is very diffrent to the way D 
> behaves anywhere else in the language.

is expressions are very similar to template parameters, IIRC they 
use the same mechanisms. You can do this for example:

void foo(T, A = T)() {
     pragma(msg, A);

alias f = foo!int;
Here the symbol T is also put in scope immediately so it can be 
used later in the parameter list.

> What do you think?

I think they have a learning curve and can be unintuitive. I 
still sometimes have to think whether to place the pattern left 
or right of the ==. However, I've grown to like them. I 
especially like using them when 'switching' over a generic type:

static if (is(T == struct) || is(T == union)) {

} else static if (is(T == E*)) {

} else static if (is(T == E[n], E, int n)) {

} else static if (is(T E == enum)) {


It's uniform, it's clear what each branch represents, it does not 
require importing and instantiating templates. Compare that to:
import std.traits;
static if (isAggregateType!T) {

} else static if (isPointer!T) {
     alias E = PointerTarget!E;
} else static if (__traits(isStaticArray, T)) {

} else static if (is(T E == enum)) {


With traits, you might have to look up the documentation to read 
it. (E.g. isAggregateType also accepts class and interface, but 
would you know that immediately? Does isIntegral!char or 
isIntegral!bool hold?). Also they are not complete (there is 
trait for checking if something is an enum), though that can be 
worked on. (I know there's a Pull Request in dmd for adding 

The advantage of traits is that they can be more future proof 
however. `isIntegral` would still work unlike `is(T : long)` even 
if `cent` and `ucent` types are added, or even if (ulong : long) 
implicit conversion gets deprecated.

I wish the redundant traits (isAssociativeArray, isStaticArray) 
weren't there since they are completely covered by is expressions 

More information about the Digitalmars-d mailing list