lazy evaluation of logical operators in enum definition

Shachar Shemesh shachar at weka.io
Wed Apr 18 04:44:23 UTC 2018


On 17/04/18 13:59, Simen Kjærås wrote:
> There's a kinda neat (and kinda ugly) way to implement prop in one line:
> 
>      enum prop(T) = __traits(compiles, { static assert(T.member == 3); });
> 
> Now, that's not the same as short-circuiting, and only useful in some 
> cases, but for those cases, it's useful.

Also, extremely dangerous.

Seriously, guys and gals. __traits(compiles) (and its uglier sibling, 
is(typeof())) should be used *extremely* sparingly.

The problem is that just about any use of __traits(compiles) I know of 
is seeking to weed out one particular reason for the compilation 
failure. There is a known bug in D, however, that the compiler 
consistently fails to read the programmer's mind. The compiler only 
knows that the code as provided does not compile, and that in that case 
you asked for something to happen.

The usual outcome is that 80-90% of the times your code does what you 
expect, but then something comes along that throws you off the beaten 
track. In those cases, instead of getting an error message, you get one 
of the sides of the "if", which results in random behavior by your code.

If you're lucky, you will get an error message much further down the 
compilation line, and then start having a fun day of trying to figure 
out what the !*#()%&!@#)!@( just happened. If you're less lucky, the 
code will actually compile.

My personal rule of thumb is this: If there is *any* way of achieving 
the result I want without __traits(compiles), do it that way.

Shachar


More information about the Digitalmars-d mailing list