Pattern matching is-expressions
Adam D. Ruppe
destructionator at gmail.com
Wed Aug 19 12:56:37 UTC 2020
On Wednesday, 19 August 2020 at 09:53:41 UTC, Stefan Koch wrote:
> pragma(msg, is(typeof(invert) == void
> function(double[]))); // false ???
> pragma(msg, is(typeof(invert) == R function
> (A), R, A)); // also false, that would suggest that
> typeof(invert) is actually function without return type or
> parameters.
Same mistake on both of these, to get a function pointer you must
use &.
// true!
pragma(msg, is(typeof(&invert) == R function (A), R, A));
And it does indeed set both R and A to the correct types.
package void invert(double[] from, int a) {
static if(is(typeof(&invert) == R function (A), R, A...)) {
pragma(msg, R); // void
pragma(msg, A); // (double[], int)
}
}
The is expression isn't as limited as you think!
> That is a problem if you don't have room for Bernd at your home.
Then don't ask for his name! The spec says if you give an
identifier there, the compiler gives it to you. You can just omit
that and do
class A {}
pragma(msg, is(A == super)); // true, no new symbol
The is expression is confusingly documented, I didn't really
realize it until I was writing a section on it in my D Cookbook
but it basically just mirrors a variable declaration with a lot
of optional parts. Using more or less of these optional parts is
how you get to the seven forms the dlang.org docs mention.
is(A)
is(A B) // only accepted inside static if though
is(A == C) // adding optional specifier
is(A B == C) // adding optional specifier and alias
As for the lifetime of the added symbols, the spec prohibits is(A
B) outside static if, but indeed, the others are allowed in other
places.
And then the names outlive the static if itself which I
complained about in bugzilla not long ago:
https://issues.dlang.org/show_bug.cgi?id=21078
So there could be a little tweak/fix to the scope lifetime of
these symbols but it does overall work really quite well and
there's ways to avoid at least some of the symbols if you like
and maybe the others should be able to be set to local or
whatever too.
But it does do a LOT of useful things.
More information about the Digitalmars-d
mailing list