template<class out_type,class in_value>
out_type convert(const in_value &t)
{
stringstream stream;
stream.clear();//清空流
stream << t;//向流中传值
out_type result;//这里存储转换结果
stream >> result;//向result中写入值
return result;
}
利用stringstream流的输入输出可以将基本数据类型转化为其他类型。
整个可以利用下列程序进行测试,在这里没用加防错及纠错处理,敬请见谅。
#include <cstdlib>
#include <string>
#include <iostream>
#include <sstream>
using namespace std;
template<class out_type,class in_value> out_type convert(const in_value &t);
int main(){
int i = 100;
double d = 111.1;
float f = 1.0f;
string iStr = convert<string, int>(i);
string fStr = convert<string, float>(f);
string dStr = convert<string, double>(d);
cout << "After a convertion, " << endl;
cout << "the number is :" << iStr << endl;
cout << "the float is :" << fStr << endl;
cout << "the double is :" << dStr << endl;
cout << "After another convertion, " << endl;
int str2Int = convert<int, string>(iStr);
float str2f = convert<float, string>(fStr);
double str2d = convert<double, string>(dStr);
cout << "the number is :" << str2Int << endl;
cout << "the float is :" << str2f << endl;
cout << "the double is :" << str2d << endl;
return 0;
}
template<class out_type,class in_value>
out_type convert(const in_value &t)
{
stringstream stream;
stream.clear();//清空流
stream << t;//向流中传值
out_type result;//这里存储转换结果
stream >> result;//向result中写入值
return result;
}