21

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.

3
  • 1
    Does this answer your question? Why is there no implicit conversion from std::string_view to std::string? Commented Nov 25, 2021 at 15:50
  • 1
    @ph This is another question, whereas this question is "Why is there no explicit not templated std::string constructor from std::string_view?" Commented Nov 25, 2021 at 16:13
  • @phuclv S.M. is correct, I'm not questioning explicitness of the constructor Commented Nov 25, 2021 at 16:42

1 Answer 1

20

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/issue2758

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Is this the only ambiguity? Can you possibly elaborate what other adjustments were added later?
@oliora I read "other adjustements" to mean the deduction guides.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.