Re: Implicit conversion to std::string --- bad idea? (really?)
On 17 Okt., 11:57, Lance Diduck <lancedid...@nyc.rr.com> wrote:
So I may have
struct A:protected std::string{
A(char const*e=""):std::string(e){
if (size()>10)throw 1;}
operator std:string const&()const{
return *this;
}
};
This special combination of inheritance and conversion
operator will never activate the conversion operator due to
[class.conv.fct]/1:
"[..] A conversion function is never used to convert a (possibly
cv-qualified) object to the (possibly cv-qualified) same object
type (or a reference to it), to a (possibly cv-qualified) base class
of that type (or a reference to it), or to (possibly cv-qualified)
void."
Similar problem here:
This is an example where a modifiable conversion is possible (at least
conceptually)
struct B:protected std::string{
B(std::vector<char> const&e)
:std::string(e.begin(),e.end()){}
operator std::string &(){
return *this;}
operator std::string const&()const{
return *this;}
};
Besides the inheritance issue your explanations make
sense, of-course.
So just ask yourself: can the class you are implicitly converting to
honor your invariant? If not, at least return a copy, or make the
conversion const. Better yet, make it explicit.
Yes, I have a similar position. While in the first years of
C++ implicit conversions have been viewed as a great
advantage, they became overused and people recognized
that they also provide the danger of ambiguities or even
worse: Silent, but unexpected conversions. Current
tendencies are to emphasize explicit approaches, e.g.
the invention of explicit c'tors, and most recently: explicit
conversion operators.
Greetings from Bremen,
Daniel Kr?gler
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]