题目
使用stringstream构建函数模板,实现任意类型转换
Stream class to operate on strings.
Objects of this class use a string buffer that contains a sequence of characters. This sequence of characters can be accessed directly as a object, using member .
Characters can be inserted and/or extracted from the stream using any operation allowed on both input and output streams.
stringstream类支持面向字符串的输入和输出,可以用于对同一个字符串的内容交替读写,同样是由两个逻辑子流构成。
template<class out_type,class in_type>
out_type convert(const in_type& in){
stringstream ss;
out_type result;
ss<<in; //向流中传入待转换的值
ss>>result; //将转换后的值写入result
ss.str(); //str()清空流的内存缓冲,重复使用内存消耗不再增加
return result;
}
int main()
{
cout<<convert<string>(123)<<endl;
cout<<convert<int>("456")<<endl;
return 0;
}