Implementing toString() and fromString() using std::stringstream
August 16th, 2009 § 1 Comment
The classes istringstream and ostringstream can be utilized to create generic templated toString() & fromString() functions. This functionality (which is built-in in many languages, such as Java) may come in very handy, quite often.
Here’s a proposed implementation for such a request:
#include <iostream>
#include <string>
#include <sstream>
template <typename T>
std::string toString (const T &t) {
std::ostringstream os;
os << t;
return os.str();
}
template <typename T>
T fromString (const std::string &str) {
std::istringstream is(str);
T t;
is >> t;
return t;
}
int main () {
std::string three("3");
int two=2;
std::cout << fromString<int>(three) << std::endl;
std::cout << toString(two) << std::endl;
}
It is important to note that the type T has some constraints:
- In toString(): there must be an operator overloading of the form operator<<(ostream&, const T&).
- In fromString(): there must be an operator overloading of the form operator>>(istream&, const T&), a default constructor for T, and a copy constructor for it.
Other than that, the technique is very useful.
Tip: boost::lexical_cast is also worth checking out (link) as it basically offers the same functionality, with some extra error checking.
Already seen on developpez.com