Hi all. I've posted here before, and with your help sorted out my last issues. However, I've gotten stuck again on part 2 of that question. I'm having problems overloading the << operator in a template class, while still having it able to access private variables.
template <typename T> ostream &operator<<(ostream & out, const Set<T> & s)
{
for (int i = 0; i < s._s.size(); i++)
{
out << s[i];
}
out << "\n";
}
template <typename T> istream &operator>>(istream & in, Set<T> & s)
{
int a;
in >> a;
s.add(a);
}
My issue is that ostream cannot access _s in the Set s, as _s is a private variable. My understanding is that declaring them as a friend should allow them to access it fine?
Here's the compiler error:
1 2 3 4
set.h: In function ‘std::ostream& operator<<(std::ostream&, const Set<T>&) [with T = double]’:
a2q2.cpp:23: instantiated from here
set.h:37: error: ‘std::vector<double, std::allocator<double> > Set<double>::_s’ is private
set.h:44: error: within this context
Oh, and just thought I should add, I've overloaded other operators (such as ==) without any hassles. It's only the friend classes that are giving me grief.
Yes, template friends are a bit of a catch. I usually just define them inline (in the class definition), since templates go into headers anyway. If you really need to put it out of line, see C++ FAQ: http://www.parashift.com/c++-faq-lite/templates.html#faq-35.16