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



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

struct S {
std::string str;
S(std::string_view str_view) : str{ str_view } { }
};

但是这个不编译?

void foo(std::string) { }
int main() {
std::string_view str_view{ "text" };
foo(str_view);
}

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

如何正确调用foo()?

您要调用的构造函数是

// 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() );

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

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

对于foo(str_view),您依赖于编译器隐式地将string_view转换为string,并且由于显式构造函数,您将获得编译器错误。要解决这个问题,你需要明确地像foo(std::string{str_view});

我应该如何正确调用foo() ?

:

foo(std::string{str_view});

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

是对std::string的显式转换。它可以调用显式转换构造函数。

但是这个不编译?

是对std::string的隐式转换。它不能调用显式转换构造函数。

最新更新