template<>
std::string operator+(std::string const& s, int const& i) {
//return s + i, that is the same as
std::stringstream ss;
ss << s << i;
return ss.str();
}
but without recurring to std::stringstream.
I would say that the specializations needed would be all the basic types except char.
std::string::operator+() will take a C string (and some other stuff) of characters of the same size as the left string operand.
In other words, if str is a wstring and s is a wchar_t *, you can do str+s.
cout << s;
should print something like "a float basic type: 100.52"
You cant do this.
I don't understand why, since there's specializations of the op+ for char basic type.
One would guess the other basic types would also have one.
Why don't they?
You might say that would create collisions.
Namely, when the string is of type unsigned short (as I imagine Unicode strings would be) the expected behaiviour would be
unsigned short us = 65535;
unicode_string += us;
here there are two possibilities:
1st unicode_string contains "ushort: 65535"
2nd unicode_string contains "ushort: ?"
where ? is the unicode character with code 65535, whichever that one is.
Solution...
template<typename T>
basic_string<T, traits<T>, Alloc<T> > operator+(
basic_string<T, traits<T>, Alloc<T> > const& s,
T const& t)
{
//same type, so we just add the character with that value?
}
template<typename T1, typename T2>
basic_string<T1, traits<T1>, Alloc<T1> > operator+(
basic_string<T1, traits<T1>, Alloc<T1> > const& s,
T2 const& t)
{
//different type so we "guess" the caller wants to "print" t's value...
}
of course this includes guessing. And that brings liabilities if we guess wrong and the user doesn't notice that unexpected behaiviour.
So I kind of understand that there's no such operator. I just don't know if this is the justification.
That's exactly what I want. But notice that it's not as elegant as the my proposed solution.
Writing boost::lexical_cast<string>( type ); all the time is kind of cumbersome.
Even my current solution str( number ); is not ideal, but still more usable.
I'm not trying to change the stl, but I'm interested in the reasons (history) behind this design choice. =)
Any pointers?
When I asked a colleague, his answer was that at the time strings were invented, the operations you seek were deemed more "streaming" operations than "string" optimizations.