basic_string operator <<

ISO/IEC JTC1 SC22 WG21 N2233 = 07-0093 - 2007-04-27

Lawrence Crowl


There are two problems with the current string concatenation syntax.

String concatenation has an awkward standard syntax, requiring parentheses in proportion to the number of items concatenated. For example,

std::string x, y;
((x += "a") += 'b') += y;
There is a potential concept for "simple stream-like" objects, which have the notion of appending strings. The existing basic_string has a syntax that is distinct from similar operations on streams, thus requiring, at minimum, a concept map.


We propose to add operator << member functions that are otherwise identical to the existing operator += member functions.

The resulting concatenation syntax requires no parentheses.

std::string x, y;
x << "a" << 'b' << y;

The resulting << operator syntax is common with stream.


We specifically do not propose to add formatting operations to strings. For this purpose, stringstream is the right solution.

Changes to the C++ Standard

21.3 Class template basic_string [basic.string]

To paragraph 5, subparagraph "21.3.6 modifiers", after the += operators, add

basic_string& operator<<(const basic_string& str);
basic_string& operator<<(const charT* s);
basic_string& operator<<(charT c); basic_string::operator<< [string::op<<]

After section basic_string::operator+= [string::op+=], add the following section.

basic_string& operator+=(const basic_string& str);

Returns: append(str).

basic_string& operator+=(const charT* s);

Returns: append(s).

basic_string& operator+=(charT c);

Returns: append(1,c).