Extending basic types - bool

Frits van Bommel fvbommel at REMwOVExCAPSs.nl
Fri Jan 19 05:34:36 PST 2007


inteja wrote:
> How do I make my own boolean class that operates *exactly* the same as the basic D type bool, but with extended functionality? Primarily I'm interested in overloading && and || but this isn't possible in D. typedef and alias aren't sufficient as I need extra functionality.
> 
> To use my own Bool class, currently I need the following syntax:
> 
> Bool a = new Bool(true);
> Bool b = new Bool(false);
> 
> Bool c = a.getValue() && b.getValue();
> 
> OR (by overloading functions with opCall):
> 
> Bool c = a() && b();
> 
> Either of the above still seem counterintuitive. I just want to be able to use:
> 
> Bool c = a && b;

At the bottom of http://www.digitalmars.com/d/operatoroverloading.html:
-----
Future Directions

The operators !, ., &&, ||, ?:, and a few others will likely never be 
overloadable.
-----

The reason is likely that those operators already have a definition when 
used with a class instance. They convert null references to false and 
others to true.
The reason it doesn't work for structs either is probably that Walter 
wants to keep the set of operators that can be overloaded the same for 
classes and structs.

You can get pretty close to the syntax by using opAnd though 
(overloading & instead of &&).
You might want to use a struct instead of a class though, since then 
it's an error to use &&, while for classes it will silently convert to 
bool as I said above.
Also, both bools and structs are passed by value, while classes are 
passed by reference.


More information about the Digitalmars-d-learn mailing list