2011-05-04 118 views
4

从“Thinking in C++ Volume 2”中的Thinking in Depth章节看到,如果您在模板类中具有友好的功能,则需要转发声明该功能。我提出这个例子来测试,overlaoding输出操作:模板和朋友

#include <iostream> 
using namespace std; 
/* 
template<class T> 
class X; 
template<class T> 
ostream& operator << (ostream& os, const X<T>& x); 
*/ 
template<class T> 
class X { 
    T t; 
public: 
    X(T i): t(i) {} 
    friend ostream& operator << (ostream& os, const X<T>& x) 
     { 
      return os << x.t; 
     } 
}; 


int main() 
{ 
    X<int> a(1); 
    cout << a; 
    return 0; 
} 

但它的工作原理没有提前声明,但后来我的< <外部类的定义测试:

friend ostream& operator << <>(ostream& os, const X<T>& x); (inside of the class) 

template<class T> 
ostream& operator << (ostream& os, const X<T>& x) 
{ 
     return os << x.t; 
} 

我不确定为什么在类中定义它不适用,是因为你必须明确说ostream操作符函数是一个模板? (使用<>)?

对不起,我感到困惑。

+1

C++ FAQ Lite也有这方面的一章:http://www.parashift.com/c++-faq-lite/templates.html#faq-35.16 – Cubbi 2011-05-04 21:06:59

+0

@ Cubbi:哦,所以当我定义它时在班级里面,没有必要提前申报,完美的探索,谢谢:) – Kobe 2011-05-04 21:11:36

回答

2

因为我的评论似乎令人满意,所以这是一个答案。

C++ FAQ Lite有a chapter on this,为了完整起见,可以归结为两种可能的方式来说服编译器,它在检查类X的主体时,朋友函数operator<<实际上是一个函数模板。

正如你所做的那样,一种方法是在类定义之前声明函数模板operator<<,并在类体内的朋友行中使用<>,给出了operator << <>(的显着语法。

另一种方法是在类X的主体内部定义好友模板函数的整个主体,这使得不需要前向声明。