Re: best efficient and readable way to concatenate strings (or the
best trade-offs)
On 2007-06-18 22:32, Diego Martins wrote:
Since C++ (and STL) have many ways to do string concatenation, I want
to hear (read) from you how you do to concatenate strings with other
strings and other types. The approaches I know are:
[snip ostringstream]
-- string::operator+
most advantage is we can built all the string using a one liner and
passing the result to string const &, but:
* we have to ensure all members are of string type
* to achieve that, we can use boost::lexical_cast or custom functions
to convert our types/classes to string
int n;
float x;
...
notebook.add("we bought " + toString(n) + " items at " + toString(x) +
" price");
// one liner!! :)
(but is there actually a gain doing that?)
and we have to implement toString(). which way is better?
lexical_cast? ostringstream? overloading (or specializing) for each
involved types? (ints and floats can be converted faster using some
hacks)
If you are mainly concerned with user defined types you can implement
std::string operator+(const std::string&, const myType&)
and
std::string operator+(const char*, const MyType&)
which would make it possible to write things like:
std::cout << "Value: " + myVal + "\n";
where myVal is of type MyType.
--
Erik Wikstr?m