Reputation: 341
void Foo1(string_view view) {
...
}
string str = "one two three";
Foo1("one two three"); // Implicitly convert char* to string_view
Foo1(str);
I wonder which constructor converts char* to string_view implicitly and which one converts the string to string_view implicitly?
I know constructor (4) convert const char* to string_view but what I passed is char*.
Upvotes: 7
Views: 33893
Reputation: 1
Below is how it convert from std::basic_string to std::basic_string_view.
Copy from gcc-13.2.0/libstdc++-v3/include/bits/basic_string.h
/**
* @brief Convert to a string_view.
* @return A string_view.
*/
_GLIBCXX20_CONSTEXPR
operator __sv_type() const noexcept
{ return __sv_type(data(), size()); }
Upvotes: 0
Reputation: 172924
std::string_view
has a non-explicit
converting constructor taking const char*
, which supports implicit conversion from const char*
to std::string_view
.
constexpr basic_string_view(const CharT* s);
When you say:
but what I passed is
char*
.
You're actually passing a string literal (i.e. "one two three"
), whose type is const char[14]
(including the null terminator '\0'
), which could decay to const char*
.
And std::string
has a non-explicit
conversion operator which supports implicit conversion from std::string
to std::string_view
.
constexpr operator std::basic_string_view<CharT, Traits>() const noexcept;
Upvotes: 17
Reputation: 148
It's https://en.cppreference.com/w/cpp/string/basic_string/operator_basic_string_view:
together with string_view's copy constructor (2)
Upvotes: 0