Skip to content

Instantly share code, notes, and snippets.

@danielSanchezQ
Created May 12, 2016 12:46
Show Gist options
  • Save danielSanchezQ/2eed66aff0177d2d6b0bd2fea96d3566 to your computer and use it in GitHub Desktop.
Save danielSanchezQ/2eed66aff0177d2d6b0bd2fea96d3566 to your computer and use it in GitHub Desktop.
String stream version of string transformers
#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