As a learning exercise, I have been looking at how automatic type conversion works in C++. I know that automatic type conversion should generally be avoided, but I'd like to increase my knowledge of C++ by understanding how it works anyway.
I have created a StdStringConverter
class that can be automatically converted to a std::string
, but the compiler (g++ 4.3.4 on Debian) seems not to do the conversion when the object is compared against a real std::string
(please ignore the lack of passing-by-reference and unnecessary creation of temporary objects):
#include <string>
class StdStringConverter
{
public:
explicit StdStringConverter(std::string name) : m_name(name) {}
operator const std::string () const { return m_name; }
private:
std::string m_name;
};
int main()
{
StdStringConverter converter(std::string("Me"));
const std::string name = "Me";
// Next line causes compiler error:
// no match for 'operator==' in 'converter == name'
return (converter == name) ? 0 : 1;
}
On the other hand, if I change it slightly to a CStringConverter
class, the automatic conversion does take place, although comparing char
pointers probably isn't what I intended:
#include <string>
class CStringConverter
{
public:
explicit CStringConverter(std::string name) : m_name(name) {}
operator const char* () const { return m_name.c_str(); }
private:
std::string m_name;
};
int main()
{
CStringConverter converter(std::string("Me"));
const char* name = "Me";
// Next line compiles fine, but they are not equal because the
// pointers don't match.
return (converter == name) ? 0 : 1;
}
Is there something special about the difference between a std::string
and a char*
in this context that makes the compiler not treat them the same?