0

I have two overloaded functions:

void Set(const char * str) { std::cout << "const char * setter: " << str << "\n"; }
void Set(const std::string_view & sv) { std::cout << "string_view setter: " << sv << "\n"; }

And I call Set() on a std::string. It picks the std::string_view overload rather than the const char * overload, i.e. it chooses the implicit conversion of std::string to std::string_view over std::string to const char *.

Is this a guaranteed behaviour in std::string, or was their choice arbitrary? If it is a guaranteed behaviour, how did they make it prefer the string_view conversion over the other?

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
Anton
  • 1,458
  • 1
  • 14
  • 28

1 Answers1

7

std::string has a non-explicit conversion operator to std::string_view, so it could convert to std::string_view implicitly. But std::string doesn't have a conversion operator to const char*, it can't convert to const char*. You have to call its c_str() method explicitly to get a const char*:

Set(some_string.c_str());
songyuanyao
  • 169,198
  • 16
  • 310
  • 405