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

Basile B. via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Dec 14 16:38:13 PST 2016


On Wednesday, 14 December 2016 at 22:06:35 UTC, Ali Çehreli wrote:
> On 12/14/2016 09:25 AM, Basile B. wrote:
> > On Tuesday, 13 December 2016 at 23:37:59 UTC, Timon Gehr
> wrote:
>
> >> I usually do
> >>
> >> enum code = q{expr};
> >> static if(__traits(compiles,mixin(code)))
> >>     fun(mixin(code));
> >
> > Strangely if i put this in a templated enum that doesn't work.
> > If instead i use a delegate literal it works.
> >
> > enum Compiles(string code) = is(typeof((){mixin(code);}));
> >
> > enum Compiles2(string code) = __traits(compiles, mixin(code));
>
> When you do that, the code does not match the syntax of 
> __traits(compiles). Putting the code inside a scope works at 
> least in this case:
>
> enum Compiles2(string code) = __traits(compiles, mixin('{' ~ 
> code ~ '}'));
>
> Ali

I see, it makes sense. Anyway the two templates have a common 
problem (protection attributes: data used in the code must be 
visible to the outside), so using them as a shortcut is a false 
good idea.


More information about the Digitalmars-d-learn mailing list