Boolean and String Overloads of the Assignment Operator (C++)

戏子无情 提交于 2019-12-01 05:36:30

The C++ standard defines overload resolution rules in chapter 13.3, there you find:

13.3.3.2 Ranking implicit conversion sequences [over.ics.rank]

2 When comparing the basic forms of implicit conversion sequences (as defined in 13.3.3.1)

— a standard conversion sequence (13.3.3.1.1) is a better conversion sequence than a user-defined conversion sequence or an ellipsis conversion sequence, and

— a user-defined conversion sequence (13.3.3.1.2) is a better conversion sequence than an ellipsis conversion sequence (13.3.3.1.3).

This means that the compiler will prefer a standard conversion sequence from the string literal to bool or int if available. Now, which standard conversions are relevant? In your case, these two are relevant:

4.2 Array-to-pointer conversion [conv.array]

1 An lvalue or rvalue of type “array of N T” or “array of unknown bound of T” can be converted to a prvalue of type “pointer to T”. The result is a pointer to the first element of the array.

This conversion turns the string literal, which is of type const char[N], into a const char*. The second one is:

4.12 Boolean conversions [conv.bool]

1 A prvalue of arithmetic, unscoped enumeration, pointer, or pointer to member type can be converted to a prvalue of type bool. A zero value, null pointer value, or null member pointer value is converted to false; any other value is converted to true. A prvalue of type std::nullptr_t can be converted to a prvalue of type bool; the resulting value is false.

That is the reason why the pointer is converted to bool. Since a standard conversion sequence exists, the user-defined conversion to std::string is not used.

To solve your problem, I suggest you add another overloaded version that takes const char* and make it forward the call to the const std::string& overload.

Daniel is right.

The short answer is that std::string is not a built-in type and, as such, doesn't get any magical preferential treatment. And that, unfortunately, the type of a string literal such as "hi world" is not std::string, but a pointer type which more easily converts to the built-in type bool than to the "user-defined" type std::string.

Basically, the answer is: welcome to C++.

Yes, I know, it's from the standard library and, no, it doesn't matter.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!