01-04-2010, 07:38 AM
This is a re-post of an article I originally posted on my website.
Please note that this is a code snippet, not a tutorial. It doesn't explain what the code does since I assume you are smart enough to work that out for yourself (it's pretty basic code tbh).
Introduction
Recently I've been doing some work templatifying my I/O classes, and from that have come to the conclusion that templates and streams make for the ultimate generic programming tool. One of the best changes the templates and streams has made is to my tryParse function (which works in a similar vein to the .NET TryParse functions).
Previously there were a load of these, each handling a different variable type using old C functions. Now the function has been replaced by a single templated function, and a std:tringstream.
If you try and tryParse a type a std:tringstream can't handle, it just doesn't compile; best of all is that you can still expand the function using template specialisation if you want to tryParse to your own custom types.
Please note that this is a code snippet, not a tutorial. It doesn't explain what the code does since I assume you are smart enough to work that out for yourself (it's pretty basic code tbh).
Introduction
Recently I've been doing some work templatifying my I/O classes, and from that have come to the conclusion that templates and streams make for the ultimate generic programming tool. One of the best changes the templates and streams has made is to my tryParse function (which works in a similar vein to the .NET TryParse functions).
Previously there were a load of these, each handling a different variable type using old C functions. Now the function has been replaced by a single templated function, and a std:tringstream.
If you try and tryParse a type a std:tringstream can't handle, it just doesn't compile; best of all is that you can still expand the function using template specialisation if you want to tryParse to your own custom types.
Code:
#ifndef TRYPARSE_H
#define TRYPARSE_H
#include <string>
#include <sstream>
//! Try and parse a string to another type
//! \return true if the conversion was ok, false otherwise
template <typename T>
bool tryParse(
const std::string &str, //!< String to convert
T &out //!< Output variable
)
{
std::stringstream sstream;
sstream.exceptions(std::ios::failbit | std::ios::badbit);
sstream << str;
try { sstream >> out; }
catch(std::exception&) { return false; }
return true;
}
#endif