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) {...}
The reason such a comparison cannot be ambiguous is that neither std::string
nor std::string_view
are plain types. Instead, these are class templates instantiations, and so are respective comparison operators:
template <class charT, class traits, class alloc>
constexpr bool operator==(const basic_string<charT, traits, alloc>& lhs,
const basic_string<charT, traits, alloc>& rhs) noexcept;
template <class charT, class traits>
constexpr bool operator==(basic_string_view<charT, traits> lhs,
basic_string_view<charT, traits> rhs) noexcept;
Such defined function templates do not consider any conversions. Instead, they expect the operands to be of exactly the same type, as only then the deduction succeeds (the same types can be deduced for template parameters of left and right operands), producing a viable candidate. Similarly:
template <typename T>
void foo(T, T);
foo(42, 'x'); // error
fails due to mismatch of types of arguments, as T
cannot be either int
or char
, although conversions between the two exist. Also:
struct my_string
{
operator std::string() const { return ""; }
};
std::string s;
my_string ms;
s == ms; // error
fails, because the compiler cannot deduce basic_string<charT, traits, alloc>
from my_string
, although there does exists an implicit conversion to its instantiation.
The comparison s1 == s2
does, however, work, because the implementation of the standard library is expected to provide overloads that can consider implicit conversions from any type to std::basic_string_view
(such an implicit conversion exists from std::string
to std::string_view
). This can be achieved, e.g., by inhibiting deduction for one of the parameters, as shown in the example part of [string.view.comparison]/p1:
template <class charT, class traits>
constexpr bool operator==(basic_string_view<charT, traits> lhs,
__identity<basic_string_view<charT, traits>> rhs) noexcept;
By putting the type of one of the operands in __identity
defined as template <class T> using __identity = decay_t<T>;
, it introduces a non-deduced context, creating an overload for some std::basic_string_view
and another argument implicitly convertible to the same instantiation of the std::basic_string_view
class template.