Re: operator==() of std::string and user-defined conversion
On Jan 30, 11:31 am, "koru...@gmail.com" <koru...@gmail.com> wrote:
What's so special about operator==() for std::string, that it can't be
used in the example below?
#include <iostream>
struct T {}; bool operator==(T const&, T const&) { return true; }
//typedef std::string T; //a == a and e == a fails
struct A
{
operator T() { return T(); }
};
int main(int const argc, char const* argv[])
{
A a = A();
T e = a;
e == e;
e == a;
a == a;
return EXIT_SUCCESS;
}
---
Korusef
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.
It looks something like this:
namespace std{
template <class T, class Ct, class Alloc>
bool operator==(basic_string<T,Ct,Alloc>
const&,basic_string<T,Ct,Alloc> const&,);
//what "std::string": really is
typedef basic_string<char, char_traits<char>,allocator<char> > string;
}
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
books, "More Exceptional C++" I believe, explains this well..
In the case of struct T, his operator== is not a template, and the
implicit conversion works.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]