3

Normally you can compare strings..

if (var1 == "a string") ...

But when I declare my own class with the conversion operator, like this :

class my_type {
   operator std::string() const { ... };
   ....
}

Now this :

 std::string var1("a string");
 my_type x("a string");
 if (x == "a string") ....
 if (x == var1) ....

does not work.. i.e....

error: no match for ‘operator==’ 

Of course this works :

 if ((std::string) x == var1) ....

But I want it to happen w/o explicitly casting. why does not c++ convert my_type to string for comparison.. How can I force it to do this w/o implementing the "==" operator itself ? The same goes for the other comparison operators.

thank you

PS> Btw if I implement operator which convert my_type to numbers(it is OK for my type)...like :

 operator double() const { ... };

the comparison with numbers work ok, I don't need to implement ==,etc.....

sten
  • 7,028
  • 9
  • 41
  • 63

2 Answers2

6

As pointed out here, this isn't about implicit casts, but of how operator == behaves on strings.

I however suggest you overload operator == for your class and not rely on an implicit conversion.

Community
  • 1
  • 1
Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
  • Does this answer OP's question whether it's possible to make it work without an explicit cast? – jrok Sep 11 '12 at 14:47
  • @user396672 no, your code is invalid. You're not allowed to extend the `std` namespace. – Luchian Grigore Sep 13 '12 at 14:40
  • @Luchian: athough it compiles under VC2010 and on Ideone. I only illustrate the matter, i can introduce the operator in the global namespace with the same result – user396672 Sep 13 '12 at 14:45
  • @Luchian: ... and regardles of moral acceptability of std extensions it illustrates that implicit conversions work on classes for operator overloads – user396672 Sep 13 '12 at 14:56
2

The conversion doesn't work because operator == for strings is a templated operator (function template), not an overload (see, for instance, http://en.cppreference.com/w/cpp/string/basic_string/operator_cmp for operator == declaration).

For function templates argument types must match parameters exactly (without any implicit conversions). To illustarte the difference, let's introduce an overload << operator on strings:

#include <string>

struct X
{
    operator std::string() {return "X";}
};


std::string operator << (std::string const& s1, std::string const& s2)
{
  return s1+s2;
}

int main()
{
    X x;
    x<<std::string("bla"); // compiles fine
}

It compiles fine.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
user396672
  • 3,106
  • 1
  • 21
  • 31
  • You're right, it's not about implicit conversion, but how `operator ==` works between strings. I wouldn't recommend overloading it though. – Luchian Grigore Sep 13 '12 at 15:05