The evils of __traits(compiles)

Paul Backus snarwin at gmail.com
Thu Jan 21 21:42:19 UTC 2021


On Thursday, 21 January 2021 at 21:20:50 UTC, jmh530 wrote:
>
> It's just so easy and when it works it works without requiring 
> much thought. Check out below. Not so easy to replace isAddable.
[...]
> enum bool isAddable(T) = __traits(compiles, {
>     auto temp = T.init + T.init;
> });
>
> void main() {
>     static assert(isAddable!int);
>     static assert(!isAddable!Foo);
> }

This is also a great illustration of the pitfalls of using 
__traits(compiles) without thorough unit testing, because your 
code has a bug in it that isn't covered by your tests:

     static assert(isAddable!(inout(int))); // fails


More information about the Digitalmars-d mailing list