C ++ has the correct lines, so you can use them. They are in the standard title bar. #include <string> to use them. No more buffer overflows strcat / strcpy; no more missing null terminators; no more dirty manual memory management; strings with the correct calculation and semantics of the correct values.
C ++ also has the ability to convert bools to human-readable representations. We saw hints of this earlier with iostream examples, but they are a bit limited because they can only transfer text to the console (or with fstreams, a file). Fortunately, C ++ designers were not complete idiots; we also have iostreams, which are not supported by the console or file, but by an automatically controlled string buffer. They are called string flows. #include <sstream> to get them. Then we can say:
std::string bool_as_text(bool b) { std::stringstream converter; converter << std::boolalpha << b;
Of course, we do not want to print all this. Fortunately, C ++ also has a handy third-party library called Boost that can help us here. Boost has a wonderful lexical_cast function. We can use it this way:
boost::lexical_cast<std::string>(my_bool)
Now itβs true to say that this is a higher load than any macro; String streams deal with locales that may not bother you, and create a dynamic string (with memory allocation), while a macro can produce a literal string, which avoids this. But, on the other hand, the stringstream method can be used for so many conversions between print and internal representations. You can run them back; For example, boost :: lexical_cast <bool> ("true") does the right thing. You can use them with numbers and virtually any type with the right formatted I / O operators. So they are quite versatile and useful.
And if after all this your profiling and benchmarking reveals that lexical_casts is an unacceptable bottleneck, then you should consider making some kind of macro-horror.
DrPizza Aug 27 '08 at 9:56 2008-08-27 09:56
source share