Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is there no support for concatenating std::string and std::string_view?

Since C++17, we have std::string_view, a light-weight view into a contiguous sequence of characters that avoids unnecessary copying of data. Instead of having a const std::string& parameter, it is now often recommended to use std::string_view.

However, one quickly finds out that switching from const std::string& to std::string_view breaks code that uses string concatenation as there is no support for concatenating std::string and std::string_view:

std::string{"abc"} + std::string_view{"def"}; // ill-formed (fails to compile) std::string_view{"abc"} + std::string{"def"}; // ill-formed (fails to compile) 

Why is there no support for concatenating std::string and std::string_view in the standard?

like image 595
s3rvac Avatar asked Jun 19 '17 17:06

s3rvac


People also ask

Can we concatenate two strings?

You concatenate strings by using the + operator. For string literals and string constants, concatenation occurs at compile time; no run-time concatenation occurs. For string variables, concatenation occurs only at run time.

Does C support string concatenation?

In C, the strcat() function is used to concatenate two strings. It concatenates one string (the source) to the end of another string (the destination). The pointer of the source string is appended to the end of the destination string, thus concatenating both strings.

Which function is used for string concatenation?

The strcat function is used to concatenate one string (source) at the end of another string (destination).


1 Answers

The reason for this is given in n3512 string_ref: a non-owning reference to a string, revision 2 by Jeffrey Yasskin:

I also omitted operator+(basic_string, basic_string_ref) because LLVM returns a lightweight object from this overload and only performs the concatenation lazily. If we define this overload, we'll have a hard time introducing that lightweight concatenation later.

It has been later suggested on the std-proposals mailing list to add these operator overloads to the standard.

like image 79
vitaut Avatar answered Sep 25 '22 22:09

vitaut