无意中发现的一个小模板,可以方便地进行类型转换,从而避免调用多个函数地麻烦。
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
template<class out_type, class in_value>
out_type convert_type(const in_value & t)
{
stringstream stream;
stream << t;//向流中传值
out_type result;//这里存储转换结果
stream >> result;//向result中写入值
return result;
}
int main()
{
int i = 1234;
string j= "456.2";
cout << convert_type<string,int>(i) << endl;
cout << convert_type<float,string>(j) <<endl;
cout << convert_type<int,string>(j) <<endl;
return 0;
}