【问题标题】:How to make a conversion from std::string_view to std::string如何进行从 std::string_view 到 std::string 的转换
【发布时间】:2021-12-10 22:07:00
【问题描述】:

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++ string c++17 implicit-conversion string-view


【解决方案1】:

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

像这样:

foo(std::string{str_view});

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

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

但是这个不编译?

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

【讨论】:

    【解决方案2】:

    您要调用的构造函数是

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

    【讨论】:

      猜你喜欢
      • 2021-08-11
      • 2020-04-12
      • 2021-12-04
      • 1970-01-01
      • 2020-12-09
      • 2017-02-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多