Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

implicitly convert string to string_view

void Foo1(string_view view) {
... 
}

string str = "one two three";

Foo1("one two three"); // Implicitly convert char* to string_view

Foo1(str); 

enter image description here 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*.

like image 340
echo Lee Avatar asked Jun 11 '26 20:06

echo Lee


1 Answers

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;

like image 123
songyuanyao Avatar answered Jun 13 '26 13:06

songyuanyao