Thread Rating:
  • 1 Vote(s) - 5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Code Snippet] Generic TryParse
#1
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:Confusedtringstream.

If you try and tryParse a type a std:Confusedtringstream 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
[Image: sig.php]
The little boat gently drifted across the pond exactly the way a bowling ball wouldn't.
Reply


Messages In This Thread
[Code Snippet] Generic TryParse - by MrD. - 01-04-2010, 07:38 AM
RE: [Code Snippet] Generic TryParse - by Gaijin - 01-04-2010, 09:26 AM
RE: [Code Snippet] Generic TryParse - by MrD. - 01-04-2010, 10:22 AM
RE: [Code Snippet] Generic TryParse - by Gaijin - 01-04-2010, 10:28 AM

Forum Jump:


Users browsing this thread: 1 Guest(s)