编译程序时理解了模板的使用。源码如下:
include<iostream>
#include<sstream>
#include<istream>
#include<stdexcept>
#include<string>
using namespace std;
template<typename Target,typename Source>
Target to(Source arg){
stringstream interpreter;
Target result;
if(!(interpreter<<arg)||!(interpreter>>result)||!(interpreter>>std::ws).eof())
throw runtime_error{"to<>()failed"};
return result;
}
int main(){
puts("please input something and we will change it:\n");
char s;
int n;
cin>>s;
n=to<char>(s);//调用模板时一定要赋予类型!而不是to(s)
cout<<"char s-->"<<n<<endl;
cin>>n;
s=to<int>(n);
cout<<"number n-->"<<s<<endl;
return 0;
}
主函数中的调用方法有瑕疵,暂时想不出更好的调用方法.....留着