A standard Boolean data type is now provided in C++ (and some compilers
already implement it). Three new keywords have been introduced: bool,
false and true.
Because bool is a distinct type, you can overload on it.
As an example, istream typically has operator void*() to provide a conversion that when used in an if condition, yields a 'boolean' value (a null pointer or a non-null pointer). In future this can be replaced by an operator bool() that yields a genuine true or false value.
One problem with operator bool() however, is that it gives a class all sorts of possibly unintended conversions that operator void*() doesn't have:
Conditionals now require a value that converts to bool (if, while, for, ?:, &&, ||, !) and comparison and logical operators now return bool (==, !=, <, <=, >, >=, &&, ||, !).
Integral and pointer values convert to bool by implicit comparison against zero. bool converts to int with false becoming zero and true becoming one.
Because bool is a distinct type, you can overload on it.
void process(bool b); void process(int i); void process(void* p);
This also means that a conversion to bool will be selected when a boolean value is needed - currently a conversion to void* is generally used:
class X
{
public:
operator bool();
operator int();
};
X x;
// ...
if (x) // uses operator bool()
{
}
if (x == 0) // uses operator int()
{
}
// ...
As an example, istream typically has operator void*() to provide a conversion that when used in an if condition, yields a 'boolean' value (a null pointer or a non-null pointer). In future this can be replaced by an operator bool() that yields a genuine true or false value.
One problem with operator bool() however, is that it gives a class all sorts of possibly unintended conversions that operator void*() doesn't have:
class Y
{
public:
operator bool();
};
Y y;
double d = y; // oops! uses operator bool() then
// bool=>double