Created
May 12, 2016 12:46
-
-
Save danielSanchezQ/2eed66aff0177d2d6b0bd2fea96d3566 to your computer and use it in GitHub Desktop.
String stream version of string transformers
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 <functional> | |
#include <string> | |
template<class T> | |
T getFromString(const std::string& value, std::function<T(const std::string&)> f) | |
{ | |
return f(value); | |
} | |
/* | |
auto getIntFromString = std::bind(getFromString<int>, std::placeholders::_1, [](const std::string& s)->int {std::stoi(s);}); | |
auto getFloatFromString = std::bind(getFromString<float>, std::placeholders::_1, [](const std::string& s)->float{std::stof(s);}); | |
*/ | |
auto getIntFromString = std::bind(getFromString<int>, std::placeholders::_1, | |
[](const std::string& s)->int | |
{ | |
std::stringstream ss(data); | |
int val; | |
ss >> val; | |
return val; | |
}); | |
auto getFloatFromString = std::bind(getFromString<float>, std::placeholders::_1, | |
[](const std::string& s)->float | |
{ | |
std::stringstream ss(data); | |
float val; | |
ss >> val; | |
return val; | |
}); | |
int main() { | |
std::cout << getIntFromString("12") << std::endl; | |
std::cout << getFloatFromString("12.4556") << std::endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment