如何从 std::string_view 转换为 std::string

Mic*_*hal 3 c++ string implicit-conversion string-view c++17

std::string_view下面这段从到转换的代码怎么可能编译std::string

struct S {
    std::string str;
    S(std::string_view str_view) : str{ str_view } { }
};
Run Code Online (Sandbox Code Playgroud)

但是这个不能编译?

void foo(std::string) { }
int main() {
    std::string_view str_view{ "text" };
    foo(str_view);
}
Run Code Online (Sandbox Code Playgroud)

第二个给出错误:cannot convert argument 1 from std::string_view to std::stringno sutiable user-defined conversion from std::string_view to std::string exists

应该如何foo()正确打电话呢?

Nat*_*ica 9

您尝试调用的构造函数是

// C++11-17
template< class T >
explicit basic_string( const T& t,
                       const Allocator& alloc = Allocator() );

// C++20+                                          
template< class T >
explicit constexpr basic_string( const T& t,
                                 const Allocator& alloc = Allocator() );
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,它被标记为explicit,这意味着不允许隐式转换来调用该构造函数。

由于str{ str_view }您使用字符串视图显式初始化字符串,因此这是允许的。

foo(str_view)您依赖编译器将 隐式转换string_view为 a 时string,由于显式构造函数,您将收到编译器错误。要修复它,您需要明确地像 foo(std::string{str_view});