42 lines
1.1 KiB
C++
42 lines
1.1 KiB
C++
|
#include <iostream>
|
|||
|
|
|||
|
using namespace std;
|
|||
|
|
|||
|
// 前置声明,否则会报错,因为下面的友元函数模版中使用了Pair模版
|
|||
|
template <typename T1, typename T2>
|
|||
|
class Pair;
|
|||
|
template <typename T1, typename T2>
|
|||
|
ostream &operator<<(ostream &out, const Pair<T1, T2> &p);
|
|||
|
|
|||
|
template <typename T1, typename T2>
|
|||
|
class Pair
|
|||
|
{
|
|||
|
// 使用外部实现友元函数的方式,需要添加<>空泛型标识,否则编译器会认为是重复声明
|
|||
|
friend ostream &operator<<<>(ostream &out, const Pair<T1, T2> &p);
|
|||
|
|
|||
|
private:
|
|||
|
T1 first;
|
|||
|
T2 second;
|
|||
|
|
|||
|
public:
|
|||
|
Pair(T1 f, T2 s) : first(f), second(s) {}
|
|||
|
T1 getFirst() const { return first; }
|
|||
|
T2 getSecond() const { return second; }
|
|||
|
};
|
|||
|
|
|||
|
template <typename T1, typename T2>
|
|||
|
ostream &operator<<(ostream &out, const Pair<T1, T2> &p)
|
|||
|
{
|
|||
|
out << p.getFirst() << " " << p.getSecond();
|
|||
|
return out;
|
|||
|
}
|
|||
|
|
|||
|
int main()
|
|||
|
{
|
|||
|
Pair<string, int> p1 = Pair<string, int>("x", 20);
|
|||
|
Pair<string, string> p2 = Pair<string, string>("name", "disen");
|
|||
|
// cout << p1 << endl;
|
|||
|
cout << p1 << "," << p2 << endl;
|
|||
|
return 0;
|
|||
|
}
|