echo Lee
echo Lee

Reputation: 341

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

Upvotes: 7

Views: 33893

Answers (3)

Luck
Luck

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

songyuanyao
songyuanyao

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

oleg
oleg

Reputation: 148

It's https://en.cppreference.com/w/cpp/string/basic_string/operator_basic_string_view: basic_string::operator basic_string_view()

together with string_view's copy constructor (2)

Upvotes: 0

Related Questions