static_cast vs boost::lexical_cast
Asked Answered
S

1

5

I am trying to concatenate an integer to a known string, and I have found that there are several ways to do it, two of those being:

int num=13;
string str = "Text" + static_cast<ostringstream*>( &(ostringstream() << num) )->str();

or I could also use boost libraries' lexical_cast:

int num=13;
string str= "Text" + boost::lexical_cast<std::string>(num);

Is the use of boost::lexical_cast more efficient in any way, since I already know the conversion type (int to string)? Or is static_cast just as effective, without having to rely on external libraries?

Smutty answered 22/7, 2013 at 15:3 Comment(5)
IMO, lexical_cast is much more readable. Note there is also std::to_string() in c++11.Rheinland
In your first example, why do you cast to a pointer?Higginbotham
@KonradRudolph: I originally wrote the cast was unnecessary in my answer (see the edit history), but it appears that operator << returns ostream& even if the RHS is a ostringstreamDoxia
@Armen I know that the cast itself is needed but taking the address and casting to pointer is convoluted. Just cast to reference. That’s more direct, both syntactically and conceptually.Higginbotham
@KonradRudolph: Yeah, I guessDoxia
D
8
string str = "Text" + static_cast<ostringstream*>( &(ostringstream() << num) )->str();

This is ugly and not easily readable. Adding to this the fact that lexical_cast does almost exactly this underneath we can definitely say that using lexical_cast is "better".

In C++11, however, we have to_string overloads.

string str = "Text" + to_string(num);

Which is the best option provided your compiler supports it.

See also How to convert a number to string and vice versa in C++

Doxia answered 22/7, 2013 at 15:14 Comment(2)
The cast is needed because the result of ostringstream() << num is ostream& not ostringstream&, so there is no str() member.Satiny
@MikeSeymour: Oh, OK, didn't think of it. EditingDoxia

© 2022 - 2024 — McMap. All rights reserved.