'c++17 Ambiguity when compare string_view with string
I saw both std::string_view and std::string have symmetric operator==() and for std::string it has the constructor to accept std::string_view and operator to convert itself to std::string_view. So when we try to use operator==() compare between std::string_view and std::string, is it supposed to be ambiguous?
I think there must be something wrong with my thoughts. Can anyone clarify?
Example:
std::string s1 = "123";
std::string_view s2 = "123";
// in the following comparison, will s1 use the convert operator to generate a string_view, or will s2 use string's string_view constructor to generate a string?
if (s1 == s2) {...}
Solution 1:[1]
This works because of an odd clause in [string.view.comparisons]:
Let
Sbebasic_string_view<charT, traits>, andsvbe an instance ofS. Implementations shall provide sufficient additional overloads markedconstexprandnoexceptso that an objecttwith an implicit conversion toScan be compared according to Table 62.
And Table 62 lists all of the comparison operators, with the view on either side of the expression.
Since std::string has an implicit conversion to std::string_view, it is this overload which will be chosen. Such overloads will have an exact match to the s1 == s2 case, so implicit conversions will not be considered.
Basically, this is implemented through SFINAE tools. Something like this:
template<typename Str>
std::enable_if_t<std::is_convertible_v<std::string_view, Str>, bool> operator==(const Str &rhs, const std::string_view &lhs);
Such an overload doesn't require implicit conversions, so it's better than any overload that does.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Nicol Bolas |
