無意中發現的一個小模板,可以方便地進行類型轉換,從而避免調用多個函數地麻煩。
#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;
}