I have written a program for implementation of stack. And I have one display function in it.
This is how I wrote display function at first:
template <class t>
void Mystack<t>::display()
{
for (int i = 0; i <= top; i++)
{
std::cout << input[i] << " ";
}
}
Then I was suggested by developers to write a display function to be more generic. So I wrote display function as:
template <class T>
void Mystack<T>::display(std::ostream &os) const
{
for (int i = 0; i <= top; i++)
{
os << input[i] << " ";
}
}
As per my understanding the benefit of writing above function is that now I have a generic display function which I can use to display data to console or to a file too.
Question 1: Is my understanding correct?
Now another suggestion is to write function something like:
template <typename T>
friend std::ostream& operator<<(std::ostream& s, Mystack<T> const& d) {
d.display(s);
return s;
}
Question 2: What is the benefit of having above display function? What exactly will I be able to achieve by having above display function?