Created
July 11, 2012 16:29
-
-
Save Kernald/3091558 to your computer and use it in GitHub Desktop.
Conversions from T to std::string and from std::string to T
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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