Ternary if and ~ does not work quite well
Ali Çehreli via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Mon Oct 12 11:55:18 PDT 2015
On 10/12/2015 08:39 AM, TheFlyingFiddle wrote:
> On Monday, 12 October 2015 at 05:19:40 UTC, Andre wrote:
>> Hi,
>> writeln("foo "~ true ? "bar" : "baz");
>> André
>
> "foo" ~ true
>
> How does this compile? All i can see is a user trying to append a
> boolean to a string which is obvously a type error. Or are they
> converted to ints and then ~ would be a complement operator? In that
> case.. horror.
Yes, horror and the mandatory link: :)
http://dlang.org/type.html#integer-promotions
That is why most C++ guidelines (used to) recommend against defining
'operator bool()' for user types because then objects of that type take
part in expressions as integers. The common recommendation in C++ used
to be to define 'operator void*()' instead, which is not integral but if
I remember correctly, it had its own share of issues. (Sorry, can't find
a reference for that at the moment.)
C++11 made it possible to define 'operator bool()' as 'explicit' to
prevent implicit conversion bugs.
Ali
More information about the Digitalmars-d-learn
mailing list