模板类友元函数的写法

Posted on 2008-10-25 12:05  活着就是幸福  阅读(1262)  评论(0编辑  收藏  举报
 1#include <iostream>
 2using namespace std;
 3
 4template<typename T>
 5class sample
 6{
 7public:
 8
 9    friend ostream& operator<< <T>(ostream& outconst sample<T>& operand );
10    //{
11    //    out<<"Value : "<<operand.data<<std::endl;
12    //    return out;
13    //}
14
15    friend istream& operator>> <T>(istream& in, sample<T>& operand );
16    //{
17    //    std::cout<<"Input data: ";
18    //    in>>operand.data;
19    //    return in;
20    //}
21
22    sample(T d = T()):data(d)    {}
23
24private:
25
26    T    data;
27}
;
28
29 template<typename T>
30 ostream& operator<<(ostream& outconst sample<T>& operand )
31 {
32     out<<"Value : "<<operand.data<<std::endl;
33     return out;
34 }

35 
36 template<typename T>
37 istream& operator>>(istream& in, sample<T>& operand )
38 {
39     std::cout<<"Input data: ";
40     in>>operand.data;
41     return in;

42 }

 其中,两个友元函数 operator<<(...)  和  operator>>(...)  必须要指定类型为<T>,即如下面所展示:

1friend ostream& operator<< <T>(ostream& outconst sample<T>& operand );
2friend istream& operator>> <T>(istream& in, sample<T>& operand );

 如果写成

1friend ostream& operator<< /*空缺*/ (ostream& outconst sample<T>& operand );

2friend istream& operator>> /*空缺*/ (istream& in, sample<T>& operand );

 

是可以通过编译但是无法link的。原因是这两个友元声明会被解释为引用了两个非模板函数, 而这两个函数的参数类型是类模板sample<T>的一个实例,而模板函数和同名的非模板函数可以共存。(C++ Primer Ed.3   C16.4), 导致link时找不到函数定义。

PS:另一种写法是在类模板内部直接写两个函数的定义,这样不用给两个友元函数指定<T>也没有上述的问题。