__traits(compiles, ...) with syntax errors

Petar Petar
Tue Jan 15 11:59:10 UTC 2019


On Tuesday, 15 January 2019 at 11:15:21 UTC, Atila Neves wrote:
> On Monday, 14 January 2019 at 21:47:40 UTC, Steven 
> Schveighoffer wrote:
>> How many times have you written something like:
>
> More times than I can count...
>
>>
>> void foo(T)(T t) if (__traits(compiles, t.bar())) // or 
>> is(typeof(t.bar()))
>> {
>>    t.bar();
>> }
>>
>> [...]
>
> I'm not sure how best to go about this.

Sounds like a job for `static try` too keep things DRY:

void fun(T)(T t) if (__traits(compiles, t.foo()))
{
     t.foo();
}

void fun(T)(T t) if (__traits(compiles, t.bar()))
{
     t.bar();
}

// ----v

void fun(T)(T t)
{
     static try { t.bar(); }
     else static try { t.foo(); }
     else static assert(0, T.stringof ~ "does not support neither 
`foo`, nor `bar`");
}


More information about the Digitalmars-d mailing list