Home > database >  How to override output operator (<<) as a function template outside a class template
How to override output operator (<<) as a function template outside a class template

Time:03-08

I am reading Section 2.4 of the book "C tempalte, a complete guide".

I tried to override output operator (<<) as a function template outside the class template Stack<>.

Below is my code, but it doesn't work.

#include <iostream>
#include <string>
#include <vector>

template<class T>
class Stack
{
    private:
    std::vector<T> v;

    public:
    void  push(T a);
    void  printOn(std::ostream & os) const;

    template <typename U>
    friend std::ostream& operator<< (std::ostream& out, const Stack<U> & s);

};      

template<typename T>
std::ostream& operator<< (std::ostream out, const Stack<T> & s)
{                                                        
    s.printOn(out);
    return out;
}

template<class T>
void Stack<T>::push(T a)
{                                
    v.push_back(a);               
}

template<class T>
void Stack<T>::printOn(std::ostream & out) const
{                               
    for(T const & vi : v)
    {out << vi << " ";} 
}

int main()
{
    Stack<int> s1;
    s1.push(12);
    s1.push(34);
    std::cout << s1;
}


CodePudding user response:

You are just omitting the &, which makes the operator<< inside and outside the class have different function signatures, they are both valid for std::cout << s1, hence the ambiguity

template<typename T>
std::ostream& operator<< (std::ostream& out, const Stack<T> & s)
                                   // ^
{                                                        
    s.printOn(out);
    return out;
}
  • Related