Implicit conversion and user-defined conversion

When I write the code as follows:

struct foo { operator int() const { return 1; } }; int main() { foo a, b; auto tmp = (a < b); } 

It works, but for now I am writing code as follows:

 struct foo { operator string() const { return string("foo"); } }; int main() { foo a, b; auto tmp = (a < b); } 

The compiler (clang ++) says that error: invalid operands to binary expression ('foo' and 'foo')

It is interesting why, since the string types and int types have comparison operators, but when foo has a custom int conversion, it will imply a conversion to int for comparison, however, when foo has only a user-defined string conversion, the compiler does not perform an implicit conversion, although (string)a<(string)b works well.

+6
source share
1 answer

I think the problem is that the string is not a base type. std::string is a specialization of the template, in particular std::basic_string<char>

So operator < is defined as

 template <class CharT, class Traits, class Allocator> bool operator< (const std::basic_string<CharT, Traits, Allocator> &_Left, const std::basic_string<CharT, Traits, Allocator> &_Right); 

He will work with:

 auto tmp = (static_cast<std::string>(a) < static_cast<std::string>(b)); 

Then operator < becomes:

 bool std::operator< <char, std::char_traits<char>, std::allocator<char>>(const std::string &_Left, const std::string &_Right) 
+1
source

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


All Articles