Templates in depth(Chapter 3 of Thinking in C++ Vol 2)

Templates in depth(Chapter 3 of Thinking in C++ Vol 2)Templates in depth(Chapter 3 of Thinking in C++ Vol 2)StringConv#ifndef STRINGCONV_H

#defineSTRINGCONV_H

#include
<string>

#include
<sstream>



template
<typename T>

T fromString(
conststd::string&s)

{

std::istringstream
is(s);

T t;

is>>t;

returnt;

}



template
<typename T>

std::
stringtoString(constT&t)

{

std::ostringstream s;

s
<<t;

returns.str();

}

#endif

Templates in depth(Chapter 3 of Thinking in C++ Vol 2)Templates in depth(Chapter 3 of Thinking in C++ Vol 2)StringConv.cpp1#include"StringConv.h"

2#include<iostream>

3#include<complex>

4usingnamespacestd;

5

6intmain()

7{

8inti=1234;

9cout<<"i ==""<< toString(i) <<""n";

10

11floatx=567.89;

12cout<<"x ==""<< toString(x) <<""n";

13

14complex<float>c(1.0,2.0);

15cout<<"c ==""<< toString(c) <<""n";

16cout<<endl;

17

18i=fromString<int>(string("1234"));

19cout<<"i =="<<i<<endl;

20x=fromString<float>(string("567.89"));

21cout<<"x =="<<x<<endl;

22c=fromString<complex<float>>(string("(1.0, 2.0"));

23cout<<"c =="<<c<<endl;

24

25}原文链接: https://www.cnblogs.com/zhtf2014/archive/2010/12/25/1916820.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/19257

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月7日 下午8:15
下一篇 2023年2月7日 下午8:17

相关推荐