-
-
Save andrey-malets/ca5d40f8b40256c06e38 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
#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