Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

static_cast vs boost::lexical_cast

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?

like image 863
joaocandre Avatar asked Jul 22 '13 15:07

joaocandre


1 Answers

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++

like image 176
Armen Tsirunyan Avatar answered Nov 02 '22 18:11

Armen Tsirunyan