为什么 std::string 没有直接接受 std::string_view 的构造函数?

oli*_*ora 19 c++ string constructor-overloading string-view c++17

为了允许std::stringstd::string_view模板构造函数进行构造

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

const T&仅当可转换为std::basic_string_view<CharT, Traits>链接)时才启用。

同时有专门的推演指南可以推演basic_stringbasic_string_view链接。该指南的评论说:

需要指南 (2-3),因为 std::basic_string_views 的 std::basic_string 构造函数被制作为模板,以避免在现有代码中引起歧义,并且这些模板不支持类模板参数推导。

所以我很好奇,需要有演绎指南和模板构造函数而不是简单的构造函数的歧义是什么std::basic_string_view,例如类似的东西

explicit basic_string(basic_string_view<CharT, Traits> sv, const Allocator& alloc = Allocator());
Run Code Online (Sandbox Code Playgroud)

请注意,我并不是问为什么构造函数被标记为显式。

BoP*_*BoP 19

歧义在于std::stringstd::string_view都可以从 构造const char *。这使得事情像

std::string{}.assign("ABCDE", 0, 1)
Run Code Online (Sandbox Code Playgroud)

如果第一个参数可以是字符串或 string_view,则不明确。

从这里开始,有几份缺陷报告试图解决这个问题。

https://cplusplus.github.io/LWG/lwg-defects.html#2758

第一件事是让成员将 string_view 放入模板中,这会降低他们在重载决策中的优先级。显然,这有点太有效了,所以后来又添加了其他调整。