2013-05-29 53 views
3

我想在模板類定義之外重載輸出流操作符<<模板以外的模板類的輸出流操作符的過載

實現它的模板類裏面就可以了:

template 
<typename T,int _MaxSize=10,template <class C> class Policy=NoCheck,typename Container=std::vector<T>> 
class MyContainer : public Policy<T> 
{ 
public: 
    MyContainer():p(_MaxSize){}; 
    std::ostream& operator<<(MyContainer<T,_MaxSize,Policy,Container>& obj){ }; 
private: 
    Container p; 
}; 

但是,當我試圖做模板類外:

template 
<typename T,int _MaxSize=10,template <class C> class Policy=NoCheck,typename Container=std::vector<T>> 
class MyContainer : public Policy<T> 
{ 
public: 
    MyContainer():p(_MaxSize){}; 
    friend std::ostream& operator<<(std::ostream& out,MyContainer<T,_MaxSize,Policy,Container> obj); 
private: 
    Container p; 
}; 

template 
<typename T,int _MaxSize,template <class C> class Policy,typename Container> 
std::ostream& operator<<(std::ostream& out,MyContainer<T,_MaxSize,Policy,Container> obj) 
{ 
}; 

編譯器抱怨:

warning: friend declaration ‘std::ostream& operator<<(std::ostream&, MyContainer<T, _MaxSize, Policy, Container>)’ declares a non-template function [-Wnon-template-friend] 
tempstruct.cc:39:97: note: (if this is not what you intended, make sure the function template has already been declared and add <> after the function name here) 

任何人都可以給出一個簡單的例子,如何可以輸出流操作在模板類外部定義的模塊<<

在我在這裏找到的相關文章中,每個人都在模板類中做它。

+2

只需停下來思考一下:「它真的需要成爲一個」朋友「嗎? – BoBTFish

+0

@BoBTFish我不確定答案。我曾經在我的非模板類中聲明它爲朋友。 –

+0

它使用任何'私人'成員數據或功能嗎?它有嗎? – BoBTFish

回答

5

任何人都可以給出一個簡單的例子,如何在輸出流運算符< <定義的模板類之外?

不,因爲它不簡單。我可以舉一個複雜的例子:

// Declare the class template, because we need it to declare the operator 
template <typename,int,template <class C> class,typename> class MyContainer; 

// Declare the operator, because (as the error says) templates must be declared 
// in the namespace before you can declare them friends. At this point, we can't 
// define the operator, since the class template is incomplete. 
template 
<typename T,int _MaxSize,template <class C> class Policy,typename Container> 
std::ostream& operator<<(std::ostream&,MyContainer<T,_MaxSize,Policy,Container>); 

// Define the class template 
template 
<typename T,int _MaxSize=10,template <class C> class Policy=NoCheck,typename Container=std::vector<T>> 
class MyContainer : public Policy<T> 
{ 
public: 
    MyContainer():p(_MaxSize){}; 

    // Include <> to indicate that this is the template 
    friend std::ostream& operator<< <>(std::ostream& out,MyContainer<T,_MaxSize,Policy,Container> obj); 
private: 
    Container p; 
}; 

// Finally define the operator 
template 
<typename T,int _MaxSize,template <class C> class Policy,typename Container> 
std::ostream& operator<<(std::ostream& out,MyContainer<T,_MaxSize,Policy,Container> obj) 
{ 
    // print some stuff 
}; 

在相關的帖子,我發現這裏的人做它的模板類裏面。

我會那麼做;它會簡單得多。或者,更好的是,假設它能夠充分訪問容器的內容,我將按照公共接口實現輸出。那麼你不需要朋友聲明,所以也不需要前向聲明。

+0

非常感謝Mike。這就是我想要的。我知道了。 –