Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A template class in C++

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?

like image 411
luna Avatar asked Aug 18 '10 13:08

luna


2 Answers

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
} 
  • A - Declares an ostringstream - an output stream that writes into a string
  • B - Write your object into that stream, using it's operator<<
  • C - Set *ok boolean to success/failure
  • D - Convert the stream into a standard string & return it.
like image 186
James Curran Avatar answered Nov 13 '22 11:11

James Curran


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.

like image 41
Jon Purdy Avatar answered Nov 13 '22 11:11

Jon Purdy