Skip to content

Instantly share code, notes, and snippets.

@Kernald
Created July 11, 2012 16:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Kernald/3091558 to your computer and use it in GitHub Desktop.
Save Kernald/3091558 to your computer and use it in GitHub Desktop.
Conversions from T to std::string and from std::string to T
#ifndef __CONVERT_HPP__
#define __CONVERT_HPP__
#include <iostream>
#include <sstream>
#include <string>
#include <stdexcept>
/**
* \brief Conversion error exception
*/
class BadConversion : public std::runtime_error {
public:
/**
* \brief Constructor
*
* \param s Message
*/
BadConversion(std::string const &s): std::runtime_error(s) {}
};
/**
* \brief Convert x to an \c std::string
*
* \tparam T Type to convert
* \param x Object to convert
*
* \return x converted to an \c std::string
*/
template<typename T>
inline std::string stringify(T const &x) {
std::ostringstream o;
if (!(o << x))
throw BadConversion(std::string("stringify(") + typeid(x).name() + ")");
return o.str();
}
/**
* \brief Convert a \c std::string to type T
*
* \tparam T Type to convert
* \param s Source string
* \param x Object to convert into
* \param failIfLeftoverChars If \c true, the conversion fails if the full string is not used
*/
template<typename T>
inline void convert(std::string const &s, T &x, bool failIfLeftoverChars = true) {
std::istringstream i(s);
char c;
if (!(i >> x) || (failIfLeftoverChars && i.get(c)))
throw BadConversion(s);
}
/**
* \brief Convert a \c std::string to type T
*
* \tparam T Type to convert
* \param s Source string
* \param failIfLeftoverChars If \c true, the conversion fails if the full string is not used
*
* \return Converted object
*/
template<typename T>
inline T convert(std::string const &s, bool failIfLeftoverChars = true) {
T x;
convert(s, x, failIfLeftoverChars);
return x;
}
#endif // __CONVERT_HPP__
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment