使用stringstream构建函数模板,实现任意类型转换

题目

使用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;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值