c++ - 将字符串隐式转换为 string_view

标签 c++ string implicit-conversion 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
我想知道哪个构造函数将 char* 隐式转换为 string_view,哪个构造函数将字符串隐式转换为 string_view?
我知道构造函数 (4) 将 const char* 转换为 string_view 但我传递的是 char*。

最佳答案

std::string_view有一个非 explicit converting constructor服用 const char* , 支持从 const char* 的隐式转换至 std::string_view .

constexpr basic_string_view(const CharT* s);


当你说:

but what I passed is char*.


您实际上是在传递一个字符串文字(即 "one two three" ),其类型为 const char[] ,衰减到 const char* .std::string有一个非 explicit conversion operator支持从 std::string 的隐式转换至 std::string_view .

constexpr operator std::basic_string_view<CharT, Traits>() const noexcept;

关于c++ - 将字符串隐式转换为 string_view,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63166194/

相关文章:

c# - 在 C# 中,将两个字节变量相加的结果分配给另一个字节变量会产生错误,只能分配给 int 变量

指针和结构的 C++ 邻接表

c++ - 获取 for 循环以完成其迭代(简单)

c++ - "operator bool() const"是什么意思

c - 构建一个复杂的字符串?

Python字符串精确结束,没有附加字符

c++ - static 和 const 如何解决不明确的函数调用?

c++ - 从 LPWSTR 转换为 LPTSTR

c++ - 如何避免这种类似单例的设计模式?

javascript - cmi.core.lesson_location 没有返回我存储在其中的相同字符串?