STL学习笔记(二),函数模板

#include <iostream>
#include <string>

using namespace std;

//函数模板
template <typename T>//也可以使用template <class T>声明函数模板
void print_(const T &var)
{
	cout<<var<<endl;
}

int main()
{
	int x = 1;
	string str = "abc";
	float f = 1.2;
	
	print_(x);
	print_(str);
	print_(f);

	system("pause");
	return 0;
}

#include <iostream>
#include <string>

using namespace std;

//多个参数的函数模板定义
template <class T1, class T2>
void print1(T1 &t1, T2 &t2)
{
	cout<<t1<<", "<<t2<<endl;
}

int main()
{
	int n = 123;
	string str = "abc";

	print1(n, str);
	print1(str, n);

	system("pause");
	return 0;
}
#include <iostream>
#include <string>
#include <sstream>

//将字符串转换成其他数据类型
template <typename T>
T fromString(const std::string &str)
{
	std::istringstream is(str);
	T t;
	is >> t;
	return t;
}

//将其他数据类型转换成字符串
template <typename T>
std::string toString(const T &t)
{
	std::ostringstream s;
	s << t;
	return s.str();
}

int main()
{
	int x = 123;
	std::string str = "456";

	int x1 = fromString<int>(str);
	std::string str1 = toString(x);

	std::cout<<"x1 = "<<x1<<std::endl;
	std::cout<<"str1 = "<<str1<<std::endl;

	system("pause");
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值