Created
May 18, 2012 15:11
-
-
Save timofurrer/2725779 to your computer and use it in GitHub Desktop.
C++ convert string to every type using template function
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
template <typename T> | |
T ConvertString( const std::string &data ) | |
{ | |
if( !data.empty( )) | |
{ | |
T ret; | |
std::istringstream iss( data ); | |
if( data.find( "0x" ) != std::string::npos ) | |
{ | |
iss >> std::hex >> ret; | |
} | |
else | |
{ | |
iss >> std::dec >> ret; | |
} | |
if( iss.fail( )) | |
{ | |
std::cout << "Convert error: cannot convert string '" << data << "' to value" << std::endl; | |
return T( ); | |
} | |
return ret; | |
} | |
return T( ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Doesn't work for
char
or aliases likeuint8_t
, instead of decimal conversion reads and returns one character.