C++函数模板和类模板

#include <iostream>
using namespace std;

template<typename T0>
class c_Example
{
private:
	ostream &_os;//此处的&非常重要
public:
	template<typename T>
	void swap(T& a, T& b)
	{
		T temp = a;
		a = b;
		b = temp;
	}
	template<typename T>
	c_Example(T temp,ostream &os):_os(os)//此处的&非常重要
	{
		_os << temp << endl;
	}
	void display(T0 temp)
	{
		_os << temp << endl;
	}
};


void main()
{
	c_Example<int> aa(12,cout);
	aa.display(15); 
	int a = 5, b = 6;
	aa.swap(a, b);//由于此处函数模板为T&,因此必须先定义,再传参
	cout << a << "  " << b << endl;
	system("pause");
}
其他

类模板中的函数模板成员可以分开定义和声明:
eg.

template<typename T1>
class MyObjectT
{
public:
    template<typename T2>
    void Foo(T2 v);
};

template<typename T1>
template<typename T2>
void MyObjectT<T1>::Foo(T2 v)
{
    cout << "Foo(" << v << ")" <<  endl;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值