#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;
}