Okay I’m a little stuck on trying to overload the << operator for my template class. The requirement is that the << operator must call a void print function defined for this class.
Here is the important stuff from the template header:
template <class T>
class MyTemp {
public:
MyTemp(); //constructor
friend std::ostream& operator<< (std::ostream& os, const MyTemp<T>& a);
void print(std::ostream& os, char ofc = ' ') const;
and here is my print function basically it’s a vector and prints last element to first:
template <class T>
void Stack<T>::print(std::ostream& os, char ofc = ' ') const
{
for ( int i = (fixstack.size()-1); i >= 0 ; --i)
{
os << fixstack[i] << ofc;
}
}
and here is how I have the operator<< overloaded:
template <class T>
std::ostream& operator<< (std::ostream& os, const Stack<T>& a)
{
// So here I need to call the a.print() function
}
But I am receiving an “unresolved external symbol” error. So really I guess I have two issues. The first, is the way to fix the error above. Second, once that is fixed would I just call a.print(os) inside << overload? I know it needs to return an ostream though. Any help would be greatly appreciated!
The simplest thing to do would be to leave
printpublic (as it is in your example), so the operator doesn’t need to be a friend.If you do need it to be private, then you need to declare the correct template specialisation to be a friend – your
frienddeclaration declares a non-template operator in the surrounding namespace, not a template. Unfortunately, to make a template a friend you need to declare it beforehand:Or you could define the operator inline:
For your last question:
It does indeed need to return an
ostream– so just return the one that was passed in, as in my example code.