实现一个类型转化程序:
//文件名 p3_8.h
#ifndef P3_8_H
#define P3_8_H
#include<string>
#include<sstream>
template<typename T>
T fromString(const std::string& s)//实现将string转化成T类型
{
std::istringstream is(s);
T t;
is>>t;
return t;
}
template<typename T>
std::string toString(const T& t)//将类型T转化成string
{
std::ostringstream os;
os<<t;
return os.str();
}
#endif
#include"chaper3-8.h"
#include<iostream>
#include<complex>
using namespace std;
int main()
{
int i=1234;
cout<<"i==\""<<toString(i)<<"\"\n";
float x=56.89;
cout<<"x==\""<<toString(x)<<"\"\n";
complex<float>c(1.0,2.0);
cout<<"c==\""<<toString(c)<<"\"\n";
cout<<endl;
i=fromString<int>(string("1234"));
cout<<"i== "<<i<<endl;
x=fromString<float>(string("567.89"));
cout<<"x== "<<endl;
c=fromString<complex<float>>(string("(1.0,2.0)"));
cout<<"c== "<<c<<endl;
int d;
cin>>d;
return 0;
}