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

3
下面的代码将 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);
}

第二个错误提示为:无法将 std::string_view 转换为 std::string,并且不存在从 std::string_view 到 std::string 的合适的自定义转换
我应该如何正确地调用foo()

第二个例子中出现了哪些错误?请将它们完整地复制粘贴(作为文本)到您的问题中。 - Some programmer dude
2个回答

8
您试图调用的构造函数是:
// 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});


2

如何正确地调用foo()函数?

像这样:

foo(std::string{str_view});

下面这段代码从 std::string_view 转换成 std::string 怎么可能编译通过:

它是一个明确的转换到 std::string。它可以调用明确的转换构造函数。

但这一段却不能编译通过呢?

它是一个隐式转换到 std::string。它无法调用明确的转换构造函数。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接