The evils of __traits(compiles)

jmh530 john.michael.hall at gmail.com
Thu Jan 21 21:20:50 UTC 2021


On Thursday, 21 January 2021 at 20:27:36 UTC, H. S. Teoh wrote:
> [snip]
>
> tl;dr: __traits(compiles) is evil, and should be avoided. 
> Unless you *really* mean, literally, "does this piece of code 
> compile", and you're not using that as a stand-in for some 
> other intended semantics (like "does X conform to Y's signature 
> constraints" or some such).  SFINAE is evil. >:-(
>
>
> T

It's just so easy and when it works it works without requiring 
much thought. Check out below. Not so easy to replace isAddable.

struct Foo
{
     int payload;

     Foo opBinary(string op)(Foo x)
         if (op == "*")
     {
      	return Foo(payload * x.payload);
     }
}

enum bool isAddable(T) = __traits(compiles, {
     auto temp = T.init + T.init;
});

void main() {
     static assert(isAddable!int);
     static assert(!isAddable!Foo);
}



More information about the Digitalmars-d mailing list