Re: Implicit conversion to std::string --- bad idea? (really?)
On Oct 16, 8:11 pm, Carlos Moreno <cm_n...@mailinator.com> wrote:
.. in a class that represents values of fields that are
read from a database, which naturally represent data in the form
of strings. ...
.... would an implicit conversion (to string) operator
... be asking for trouble? In particular, are we risking subtle
bugs due to unexpected conversions?
I'll only relate my own experience with
a library we use extensively, in which
in many cases the only way to extract data
from fields is via implicit conversions.
My experience is that it is a royal pain
in the you-know-where. I've run into two
problems:
1. Having to use a cast to extract the data.
The implicit conversion works fine if you
are in a context where only one datatype
is possible. For instance:
// myField has implicit conversion
// to std::string
std::string my_value( myField ); // OK
But if your object is in an expression
in which the data type is not determined
by the context, you may have problems:
f( myField + "/" ); // may not work.
f( std::string( myField ) + "/" ); // OK, but ugly
If the library had an extraction member function,
I would _never_ use the implict conversion.
2. If you have multiple implicit conversions,
expressions may be ambiguous, or, worse,
you may get the wrong one.
Our library has conversions to and from
"long" and "char", which makes conversions
to/from "int" ambiguous. More casts. :(
Also, if you have, say, 2-arg. functions,
such as comparisons, defined for your
field object, what is the compiler
going to do with something like this?
if ( my_field == my_string )
I've also had implicit conversions done
when I didn't expect any conversion at all.
Overall, I'm leery of implicit conversions.
I'd say they might be OK if:
a. The conversion never loses information
or functionality, _and_
b. There's no conversion the other way.
I am _so_ grateful that the C++ Standard
folks did _not_ include an implicit conversion
from std::string to const char * !
(When I want that effect, I'm happy to write:
void f( const char * );
void f( const std::string &a ) { f( a.c_str() );}
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]