Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't std::string have a constructor that directly takes std::string_view?

To allow std::string construction from std::string_viewthere is a template constructor

template<class T>
explicit basic_string(const T& t, const Allocator& alloc = Allocator());

which is enabled only if const T& is convertible to std::basic_string_view<CharT, Traits> (link).

In the meantime there is a special deduction guide to deduce basic_string from basic_string_view (link). A comment to the guide says:

Guides (2-3) are needed because the std::basic_string constructors for std::basic_string_views are made templates to avoid causing ambiguities in existing code, and those templates do not support class template argument deduction.

So I'm curious, what is that ambiguity that requires to have that deduction guide and template constructor instead of simply a constructor that takes std::basic_string_view, e.g. something like

explicit basic_string(basic_string_view<CharT, Traits> sv, const Allocator& alloc = Allocator());

Note that I'm not asking why the constructor is marked explicit.

like image 919
oliora Avatar asked Nov 25 '21 15:11

oliora


People also ask

Is string the same as std::string?

There is no functionality difference between string and std::string because they're the same type.

What is std:: string_ view for?

std::string_view provides read-only access to an existing string (a C-style string literal, a std::string , or a char array) without making a copy.

Is std::string movable?

Yes, std::string (since C++11) is able to be moved i.e. it supports move semantics.

Why do we use std::string?

std::string class in C++ C++ has in its definition a way to represent a sequence of characters as an object of the class. This class is called std:: string. String class stores the characters as a sequence of bytes with the functionality of allowing access to the single-byte character.


Video Answer


1 Answers

The ambiguity is that std::string and std::string_view are both constructible from const char *. That makes things like

std::string{}.assign("ABCDE", 0, 1)

ambiguous if the first parameter can be either a string or a string_view.

There are several defect reports trying to sort this out, starting here.

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

The first thing was to make members taking string_view into templates, which lowers their priority in overload resolution. Apparently, that was a bit too effective, so other adjustments were added later.

like image 120
BoP Avatar answered Oct 16 '22 21:10

BoP