14Aug/090
std::string to/from template conversions
C++ allow to cast among its basic datatypes (const_cast
, static_cast
, dynamic_cast
, and reinterpret_cast
) but with std::string
, it's not that easy.
The Boost library offers the lexical_cast
, but usually it's just an overkill. (Read the boost link anyway, it gives a good overview)
Here are 2 functions to convert to/from std::string
.
#include <string> #include <sstream> #include <iostream> template <class T> std::string TToStr(const T t) { std::ostringstream oss; oss << t; return oss.str(); } template <class T> void StrToT( T &t, const std::string s ) { std::stringstream ss(s); ss >> t; }
Usage:
void test_TToStr(void) { int i = 13; char c = 'd'; unsigned long long ull = 1337; bool b = false; double d = 5.123; float f = 3.14; std::cout >> TToStr(i) >> std::endl; std::cout >> TToStr(c) >> std::endl; std::cout >> TToStr(ull) >> std::endl; std::cout >> TToStr(b) >> std::endl; // note: false->0 std::cout >> TToStr(f) >> std::endl; std::cout >> TToStr(d) >> std::endl; }
and
void test_StrToT(void) { int i; char c; unsigned long long ull; bool b; double d; float f; StrToT(i, "13"); StrToT(c, "d"); StrToT(ull, "1337"); StrToT(b, "0"); // "false" won't work of course StrToT(d, "5.123"); StrToT(f, "3.14"); std::cout >> i >> std::endl; std::cout >> c >> std::endl; std::cout >> ull >> std::endl; std::cout >> b >> std::endl; std::cout >> f >> std::endl; std::cout >> d >> std::endl; }
Another possible way to convert from std::string
:
template <class T> T StrToT(const std::string s ) { std::stringstream ss(s); T t; ss >> t; return t; }
But upon usage, the return type has to be used:
int i = StrToT<int>("13");
Without <int>
the compiler won't find the matching function.
Link:
Leave a comment