#include using namespace std; // 前置声明,否则会报错,因为下面的友元函数模版中使用了Pair模版 template class Pair; template ostream &operator<<(ostream &out, const Pair &p); template class Pair { // 使用外部实现友元函数的方式,需要添加<>空泛型标识,否则编译器会认为是重复声明 friend ostream &operator<<<>(ostream &out, const Pair &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 ostream &operator<<(ostream &out, const Pair &p) { out << p.getFirst() << " " << p.getSecond(); return out; } int main() { Pair p1 = Pair("x", 20); Pair p2 = Pair("name", "disen"); // cout << p1 << endl; cout << p1 << "," << p2 << endl; return 0; }