Reputation: 4211
I noticed that
std::string str;
str += 'b'; // works
str.append('b'); // does not work
str.append(1, 'b'); // works, but not as nice as the previous
Is there any reason why the append
method does not support a single character to be appended? I assumed that the operator+=
is actually a wrapper for the append
method, but this does not seem to be the case.
Upvotes: 12
Views: 2265
Reputation: 30604
It is interesting to note that the form of append
here;
string& append( size_type count, CharT ch );
Mirrors the constructor taking similar input.
basic_string( size_type count,
CharT ch,
const Allocator& alloc = Allocator() );
And some other methods that take a count
with a character, such as resize( size_type count, CharT ch );
.
The string class is large and it is possible that the particular use case (and overload) for str.append('b');
was not considered, or the alternatives were considered sufficient.
Just simple the introduction of a single overload for this could introduce ambiguity if the integrals int
and char
correspond (on some platforms this may be the case).
There are several alternatives to the append
adding a single character.
str.append("b");
. Albeit that this not exactly the same, it has the same effect.operator+=
push_back()
, which is consistent with other standard containersPoint is, it was probably never considered as a use case (or strong enough use case), thus, a suitable overload/signature was not added to append
to cater for it.
Alternative designs could be debated, but given the maturity of the standard and this class, it is unlikely they will be changed soon - it could very well break a lot of code.
Alternate signatures for append
could also be considered; one possible solution could have been to reverse the order of the count
and char
(possibly adding a default);
string& append(CharT ch, size_type count = 1);
Another, as described in some of the critique of basic_string
is to remove append
, there are many methods to achieve what it does.
Upvotes: 2
Reputation: 70333
I figure that operator+=()
is intended to handle all the simple cases (taking only one parameter), while append()
is for things that require more than one parameter.
I am actually more surprised about the existence of the single-parameter append( const basic_string& str )
and append( const CharT* s )
than about the absence of append( CharT c )
.
Also note my comment above: char
is just an integer type. Adding a single-parameter, integer-type overload to append()
-- or the constructor (which, by design, have several integer-type overloads already) might introduce ambiguity.
Unless somebody finds some written rationale, or some committee members post here what they remember about the discussion, that's probably as good an explanation as any.
Upvotes: 6