例子:
#include <iostream>
#include <string>
/**
*@brief 将T类型转换为string
*@param val
*@return string
*/
template<class T> string convertToString(const T& val)
{
ostringstream s;
//T -> string
if (!(s << val))
{
std::cout << "can't convert form T type to string type !" << std::endl;
}
return s.str();
}
/**
*@brief 将string转换为T类型
*@param val
*@return string
*/
template<class T> T convertToString(const string& str)
{
istringstream s(str);
T buf;
//string -> T
if (!(s >> buf))
{
std::cout << "can't convert from string type to T type !" << std::endl;
}
return buf;
}
参考: