Search code examples
c++stringimplicit-conversionstring-view

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*.


Solution

  • 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;