37 lines
833 B
C++
37 lines
833 B
C++
|
#include <iostream>
|
||
|
|
||
|
using namespace std;
|
||
|
|
||
|
template <typename T1, typename T2>
|
||
|
class Pair
|
||
|
{
|
||
|
// 使用友元函数模版的方式,可以避免重复声明
|
||
|
template <typename U1, typename U2>
|
||
|
friend ostream &operator<<(ostream &out, const Pair<U1, U2> &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 U1, typename U2>
|
||
|
ostream &operator<<(ostream &out, const Pair<U1, U2> &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;
|
||
|
}
|