Skip to content

Instantly share code, notes, and snippets.

@andrey-malets
Last active August 29, 2015 14:27
Show Gist options
  • Save andrey-malets/ca5d40f8b40256c06e38 to your computer and use it in GitHub Desktop.
Save andrey-malets/ca5d40f8b40256c06e38 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <sstream>
#include <type_traits>
template<bool is_function, typename T> struct Parser;
template<typename T> struct Parser<true, T> {
static void Parse(const std::string& input, T& parser) {
parser(input);
}
};
template<typename T> struct Parser<false, T> {
static void Parse(const std::string& input, T& value) {
std::istringstream(input) >> value;
}
};
template<typename T> void Parse(const std::string& input, T&& value) {
constexpr bool is_function =
std::is_convertible<T, std::function<void(const std::string&)>>::value;
Parser<is_function, T>::Parse(input, value);
}
void parse_float(const std::string& value) {
std::cout << atof(value.c_str()) << std::endl;
}
int main(void) {
std::string a("123"), b("45.6"), c("1e10");
int i;
double d;
Parse(a, i);
Parse(b, [&d](const std::string& input) {
d = atof(input.c_str());
});
std::cout << i << " " << d << std::endl;
Parse(c, parse_float);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment