__traits(compiles) is true with warnings as errors
notrealemail at gmail.com
Thu Oct 14 05:41:01 UTC 2021
On Wednesday, 13 October 2021 at 17:58:23 UTC, Jonathan Levi
> When dmd is passed the "-w" tag, it "treats warnings as errors"
> but not with the "__traits(compiles)" expression. Is this the
> intended action?
> This code should compile even with "-w", but it does not.
> int i;
> static if (__traits(compiles,i += 5.2))
> i += 5.2;
> `pragma(msg, __traits(compiles,i += 5.2))` is `true`, even
> though it will stop the compiler.
> My specific use case, where I am hindered by this, is with a
> guarded template function akin to this:
> void fun(T,U)(ref T a, const U b)
> if (__traits(compiles, a += b))
> a += b;
> I think this is a bug. The Docs for __traits compiles state
> "Returns a bool true if all of the arguments compile . . ."
> which is not holding true.
But it _is_ compiling, just with a warning.
If you wish to force the code to compile, you can manually cast
it to prevent the compiler from erroring out:
static if (__traits(compiles,i += 5.2))
i += cast(int)5.2;
Or in general:
void fun(T,U)(ref T a, const U b)
if (__traits(compiles, a += b))
a += cast(T)b;
It seems the `__traits(compiles, ..)` feature was designed to
operate independent of the command line flags passed to the D
I don't know if that's a bug or not though; best wait for someone
more experienced to chime in.
More information about the Digitalmars-d-learn