为什么在 C++ 标准中没有 std::basic_string 类的构造函数,其类型为 std::string_view 的参数

Vla*_*cow 2 c++ string constructor string-view c++17

标准类std::basic_string没有接受类型对象作为其参数的“隐式”构造函数的原因是什么std::string_view

我希望这个程序能够编译。

#include <iostream>
#include <string>
#include <string_view>

struct A
{
    void f( const char *s ) const
    {
        std::cout << "A::f( " << s << " )\n";
    }        
};

struct B
{
    void f( const std::string &s ) const
    {
        std::cout << "B::f( " << s << " )\n";
    }        
};

template <typename... Bases>
struct C : Bases...
{
    using Bases::f...;
};

int main()
{
    C<A, B>().f( std::string_view( "Hello" ) );
    // or
    std::string_view s( "Hello" );
    C<A,B>().f( s );
}
Run Code Online (Sandbox Code Playgroud)

Nat*_*ica 5

原因是因为许多string_view接受函数与std::string同一函数的重载不明确。拿

std::string s({"abc", 1});
Run Code Online (Sandbox Code Playgroud)

例如。这是通过调用接受构造函数std::string从 a创建 a 或创建一个viastd::string_viewstring_viewstd::string

basic_string(const CharT* s, size_type count, const Allocator& alloc = Allocator());
Run Code Online (Sandbox Code Playgroud)

LWG 2758最初提出了这个问题,LWG 2946完成了string_view对模板的所有获取功能的调整。通过这样做,旧的字符串接口不需要调整,所以旧的代码在 C++17 下编译时不会中断。

  • 这种黑客行为的全部目的是避免破坏现有代码。现有代码是否可以用其他方式重写并不重要。 (2认同)