24.1. operator int() const
Prior to the introduction of the bool keyword to the language, the most obvious form of such a thing might have been to provide operator int() const, as in:
Listing 24.1.
class ExpressibleThing
{
public:
operator int() const;
};
ExpressibleThing e;
if(e) // Evaluates whether e "is"
{}
if(!e) // Evaluates whether e "is not"
{}
The big problem with this is that an int is readily convertible to many other types, and it can be meaninglessly used in the construction of an entirely unrelated type:
ExpressibleThing e;
std::vector<String> vs(e); // What on earth does this mean?!
This is meaningless, and also a potential source of undefined behavior. Since Expressible Thing need only return any non-zero value, it could be correctly implemented to return a different non-zero value each time it is called. This could result in a silent failure, or cause memory exhaustion, or, worse, could actually work correctly in most cases: operator int() const might return 1,000, which is always large enough for the subsequent uses of vs, throughout your testing but not enough when your product goes live.
|