Created
August 4, 2015 16:16
-
-
Save mrdomino/5f13833c9926233ddd85 to your computer and use it in GitHub Desktop.
sstream-driven lexical cast
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
#pragma once | |
#include <sstream> | |
#include <string> | |
namespace detail { | |
template <typename T, typename U> | |
class LexicalCast { | |
public: | |
T operator()(U const& u) { | |
return string_to_t(u_to_string(u)); | |
} | |
private: | |
LexicalCast<T, std::string> string_to_t; | |
LexicalCast<std::string, U> u_to_string; | |
}; | |
template <typename T> | |
class LexicalCast<std::string, T> { | |
public: | |
std::string operator()(T const& t) { | |
std::ostringstream os; | |
os.exceptions(os.failbit | os.badbit); | |
os << t; | |
return os.str(); | |
} | |
}; | |
template <typename T> | |
class LexicalCast<T, std::string> { | |
public: | |
T operator()(std::string const& s) { | |
T t; | |
std::istringstream is(s); | |
is.exceptions(is.failbit | is.badbit); | |
is >> t; | |
return t; | |
} | |
}; | |
} // namespace detail | |
template <typename T, typename U> | |
T lexical_cast(U&& value) { | |
static detail::LexicalCast<T, U> cast; | |
return cast(std::forward<U>(value)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment