This is a nifty static if trick I picked up recently (I think I saw it first in some of Andrei's code).
The situation is that you want to check at compile time if some bit of code is valid or not. Say you want to know if type T supports concatenation by type S using the ~= operator. Bascially you want to know if this will compile or not:
T x;
S y;
x ~= y;
The cool trick is to just put that code in an anonymous delegate and use typeof to see if it compiles.
static if (is(typeof({T x; S y; x~=y;}))) {
/* do something */
}
else {
/* do something else */
}
If it compiles, the typeof() will return void delegate() and is() will be true, if it doesn't compile then the tyepof will be invalid and is() will return false.
You can also use .init to avoid making variable names:
static if (is(typeof({T.init~=S.init;}))) {
/* do something */
}
else {
/* do something else */
}
Note that this is primarily for D1. In D2 there's __traits(compiles, T.init ~= S.init).