Overload output stream operator of a template class outside of the template

前端 未结 1 417
别那么骄傲
别那么骄傲 2021-01-20 23:36

I want to overload the output stream operator << outside the template class definition.

Implementing it inside the template class is ok:



        
相关标签:
1条回答
  • 2021-01-21 00:14

    Can anybody give a simple example on how can the output stream operator << defined outside a template class?

    No, because it's not simple. I can give a complicated example:

    // 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
    };
    

    In the related posts that I found here everyone do it inside the template class.

    I'd do that; it would be much simpler. Or, better still, I'd implement output in terms of the public interface, assuming it gives sufficient access to the container's contents. Then you wouldn't need the friend declaration, so wouldn't need the forward declarations either.

    0 讨论(0)
提交回复
热议问题