Created
March 9, 2011 18:56
-
-
Save mark-d-holmberg/862733 to your computer and use it in GitHub Desktop.
convert a C++ std::string to the template type you specify
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 <string> | |
#include "sstreamconvert.h" | |
int main( int argc, char **argv ) { | |
//convert a string to a double | |
double D = convert_to <double>("13.37"); | |
std::cout << "We can convert a string to a double using our neat template code" << std::endl; | |
std::cout << "The value of D is: [" << D << "]." << std::endl; | |
return 0; | |
} |
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
all: | |
g++ -Wall -g -o sstream-convert.x86 main.cpp | |
clean: | |
rm sstream-convert.x86 |
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 <sstream> | |
#include <string> | |
template <typename T> T convert_to (const std::string &str) | |
{ | |
std::istringstream ss(str); | |
T num; | |
ss >> num; | |
return num; | |
} |
Clever! I'm going to using it. It's such an easy solution instead of specialized templates. Thanks.
Glad you like it.
It's really interesing idea and it's so simple, thanks!
Thank you, it is really helpful!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You can take "12345.678" to have a try.