C++任意類型轉換模板

 

  1. #include<iostream> 
  2. #include<sstream> 
  3. #include<string> 
  4. using namespace std; 
  5.  
  6.  
  7. template<class out_type,class in_value> 
  8. out_type convert(const in_value & t) 
  9. stringstream stream; 
  10. stream<<t;//向流中傳值 
  11. out_type result;//這裏存儲轉換結果 
  12. stream>>result;//向result中寫入值 
  13. return result; 
  14.  
  15.  
  16. int main() 
  17.     string s; 
  18.     while(cin>>s) 
  19.     { 
  20.         double valdou=convert<double>(s);  
  21.         int valint=convert<int>(s);  
  22.         cout<<valdou<<endl; 
  23.         cout<<valint<<endl; 
  24.         
  25.        
  26.     } 
  27.  
  28.  
  29.     return 0; 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章