Re: operator==() of std::string and user-defined conversion
On Jan 31, 9:31 am, "Lance Diduck" <lancedid...@nyc.rr.com> wrote:
....
The short oversimplified answer is that std::string is really a
typedef for an elaborate template declaration. It turns out that
operator== is really a template function. Template functions will not
try to find a way to do an implicit conversion, but rather try to
generate a function directly to match the parameters as given.
....
The compiler cannot match struct A to any template parameters of
basic_string operator==, and ignores this template. The compiler will
not try every implict conversion in hope of finding a template
function that could possibly satisfy the expression. One of Sutters
....
That info helped a lot but it isn't actually the correct answer.
In the original for std::string the search of operator== in std
namespace isn't even considered as shown in the following more general
example.
namespace tst
{
struct G {};
template <class X> struct TT {};
template <class X>
bool operator==(TT<X> const&, TT<X> const&)
{ return true; }
template <class X, class Y>
bool operator==(TT<X> const& x, Y const& y) //have to be defined
for e == a expression
{ return x == static_cast<TT<X> >(y); }
template <class Y>
bool operator==(Y const&, Y const&)//too general, defined only for
a == a expression
{ return true; }
}
typedef tst::TT<tst::G> T;
struct A
{
operator T() const { return T(); }
};
int main(int const argc, char const* argv[])
{
using tst::operator==;
A a = A();
T e = a;
e == e;
e == a; //We have to define special operator==() for this, because
templated operator==() doesn't try conversions, but rather tries to
find matches.
a == a;//ADL doesn't even look into tst namespace for operator==()
without the using directive and we have to define special operator==()
for this case as well.
return 0;
}
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]