Why doesn't the conversion function work with std :: string?

Consider the following class that contains a conversion function for the type std :: string:

class SomeType { public: SomeType(char *value) { _str = value; } operator std::string() { return std::string(_str); } private: char *_str; }; 

The following fragment cannot be compiled with an error: not a single "==" operator matches these operands

 int main(int argc, char* argv[]) { SomeType a("test"); if (a == std::string("test")) // ERROR on this line { int debug = 1; } return 0; } 

I understand that I can define an operator == method that accepts the std :: string operand, but why does the conversion function not work?

+6
source share
2 answers

The problem is that std :: string is actually a template, and so I assume the comparison operator is also a template. And in this case, the standard, as I recall, claims that for the required arguments there will be no implicit conversion, which means that you will need to impose SomeType on the string so that it is called.

As stated in paragraph 46 of Effective C ++:

[...] because implicit type conversions are never taken into account when outputting a template argument. Never. Such transformations are used during function calls, yes, but before you can call a function, you must know what functions exist. [...]

You can find more information here .

+8
source

std::string is actually typedef to std::basic_string<char, i_do_not_remember>

There is no operator == that only get std::string This is template one.

 template<...> bool operator (basic_string<...>& a, basic_string<...>& b) { // } 

But template types cannot be deduced here. You can do it manually:

 if (static_cast<std::string>(a) == std::string("test")) 
+4
source

Source: https://habr.com/ru/post/949429/


All Articles