c++藉助stringstream實現類型轉換

無意中發現的一個小模板,可以方便地進行類型轉換,從而避免調用多個函數地麻煩。

#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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章