DRY version of `static if(__traits(compiles, expr)) fun(expr)`

Timon Gehr via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Dec 13 15:37:59 PST 2016


On 14.12.2016 00:00, Timothee Cour via Digitalmars-d-learn wrote:
> what's the best (and DRY) way to achieve:
>
> ```
> static if(__traits(compiles, expr))
>   fun(expr);
> ```
>
> ie, without repeating the expression inside expr?
>
> eg:
>
> ```
> static if(__traits(compiles, foo.bar[2])){
>   counter++;
>   writeln(" expr = ", foo.bar[2]);
> }
>
> ```
>

I usually do

enum code = q{expr};
static if(__traits(compiles,mixin(code)))
     fun(mixin(code));



More information about the Digitalmars-d-learn mailing list