What is the function of the following C++ template class? I'm after line by line annotations:
template<class T> string toString(const T& t, bool *ok = NULL) {
ostringstream stream;
stream << t;
if(ok != NULL) *ok = stream.fail() == false;
return stream.str();
}
Is it like Java's toString()
method?
Basically, it will take any object which has an operator<< defined for output to a stream, and converts it to a string. Optionally, if you pass the address of a bool varaible, it will set that based on whether or not the conversion succeeeded.
The advantage of this function is that, once defined, as soon as you defined operator<< for a new class you write, you immedaitely also get a toString() method for it as well.
template<class T>
string toString(const T& t, bool *ok = NULL)
{
ostringstream stream; // line A
stream << t; // line B
if(ok != NULL)
*ok = (stream.fail() == false); // line C
return stream.str(); // Line D
}
This templated function accepts a value of any type and a pointer to a bool
. It attempts to use a std::ostringstream
to convert the value to a std::string
using the formatting conversions supplied by output streams. If the bool
-pointer parameter is non-null, the function writes whether the stream operation succeeded to the value at that pointer.
Thus it's possible to write:
std::string s = toString(123);
But it's also possible to write:
bool succeeded;
std::string s = toString(something, &succeeded);
if (succeeded) { ... }
That is, the function allows you to check whether the conversion was successful.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With