template
class Pair{
private:
T1 key;
T2 value;
public:
template
friend ostream & operator << ( ostream & os, const Pair &r );
};
这个友元函数定义写在外面就完全没有问题,如果定义写在里面的话,如果在main函数里定义 Pair< string,int >没问题,再写Pair< double,int >就会报错,似乎是redefinition等等,请问这是什么原因呢
#include <iostream>
using namespace std;
template<class T1, class T2>
class Pair{
private:
T1 key;
T2 value;
public:
Pair(T1 k, T2 v) { key = k; value = v; }
template<class T1, class T2>
friend ostream& operator<<(ostream& out,const Pair<T1,T2>& p);
};
template<class T1, class T2>
ostream& operator<<(ostream& out,const Pair<T1,T2>& p)
{
out<<p.key<<","<<p.value<<endl;
return out;
}
int main(int argc, _TCHAR* argv[])
{
Pair<int,int> p(12,345);
cout << p;
return 0;
}