Date: 2001-08-24 10:07:50
> In the meanwhile I realized that he actually needs
> a conversion to bool,
> which is false for zero and true for non-zero,
> If I prove an implicit conversion to bool, however,
> I will also have an implicit conversion to
> all the other built-in types with confusing semantics:
> So I consider making the all the conversion operators to
> built-in types (with the only exception of bool)
> private and undefined.
One trick that I've seen for this is to provide an implicit conversion to
"void *". This allows testing, but does not allow implicit conversions to
other types (except, of course, a void pointer).
Having said that, I must also say that I personally think conversion
functions are evil; they always allow users to hurt themselves. Providing a
conversion to bool and hiding the other conversions will probably make code
such as this ambiguous (it will if your "BigInt" has an implicit conversion
a + b; // operator+(a, BigInt(b)) or bool(a) + b ?
Providing the conversion to 'void *' is a little better (it won't mess with
overloaded operators), but it still allows the user to shoot themselves in
delete a; // ouch.
void f(int x); void f(void * x); // Completely different functions
f(a); // hmmm... compiler calls the pointer version instead of the integer
or: (assuming you don't have an operator<< for BigInt's)
std::cout << a; // prints '0' or '1'...
Another method I've seen around is to just overload operator!, so that users
can test 'if (!a)' -- but then they can't do 'if (a)'.
The solution that I would do myself is to provide a member function:
'zero()'/'is_zero()', or (if the construction cost is cheap) just make the
user do 'if (a == 0)'. It makes the user-side code more explicit, which is
more typing, but also forces more clarity.
From my own personal programming experience: I *have* used conversion
operators for various reasons. However, as my code has matured over the
past serveral years, *every single one* has been removed.
"In general, it is wise to be sparing in the introduction of conversion
operators." -Bjarne Stroustrup, The C++ Programming Language (3rd ed.),
"... [Y]ou usually don't want to provide type conversion functions of _any_
ilk." -Scott Myers, More Effective C++, Item 5
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk