yank unary '+'?

Don nospam at nospam.com
Sun Dec 6 21:13:24 PST 2009


Andrei Alexandrescu wrote:
> bearophile wrote:
>> Walter Bright:
>>
>>> Think of it like the "bool" operator overload. bool gives a direct
>>> way for user defined times to be tested for if statements, etc.
>>> Similarly, U+ gives a direct way for user defined types to be
>>> converted to their most desired arithmetic type.
>>
>> I'd like opBool in D, for example to implement multiprecision numbers
>> that can be used as integers in: if (somenumber) {...
> 
> Unfortunately experience with C++ has shown that things look simpler 
> than they are. If opBool is an implicit conversion to bool, then all 
> sorts of weird expressions are allowed. That's why conversion to bool is 
> flat out unrecommended in C++. Instead, various libraries found 
> alternate ways to allow testing with if without compromising things too 
> much. Loki uses conversion to an opaque pointer type. Boost uses 
> conversion to a pointer to member. The standard itself uses, I think, 
> conversion of iostreams to void*.
> 
> In my draft spec of operators I have the test:
> 
> a ? <expr1> : <expr2>
> 
> where a is of user-defined type, rewritten as
> 
> !!a ? <expr1> : <expr2>
> 
> and the test:
> 
> if (a) <stmt>
> 
> rewritten as
> 
> if (!!a) <stmt>
> 
> This leads to perfect correspondence with the behavior of arrays, 
> pointers, class references, and integrals: you can't convert any of 
> those to bool but you can test them with if or the ternary operator. 
> Rewriting to !!a achieves exactly the same thing.
> 
> So user-defined types may define ! to return bool with the usual 
> semantics, and the compiler nicely takes care of the rest.

That's great. Simple and effective.



More information about the Digitalmars-d mailing list