I have been overloading operator<< for a few class templates without problem, but ran into this issue when I want to overload said operator for a substruct.
Here is an example:
#include <iostream>
using namespace std;
template <typename T>
class A {
public:
struct S { // note: templated on T.
S() { x = 2; }
T x;
// // doesn't work.
// template<typename T1>
// friend ostream& operator<<(ostream& os, const typename A<T1>::S& rhs) {
// os << rhs.x;
// return os;
// }
};
S s;
};
//// doesn't work.
//template<typename T>
//ostream& operator<<(ostream& os, const typename A<T>::S& rhs) {
// os << rhs.x;
// return os;
//}
// works, but not general.
ostream& operator<<(ostream& os, const typename A<int>::S& rhs) {
os << rhs.x;
return os;
}
int main() {
A<int> a;
cout << a.s << endl;
return 0;
}
The compile error is:
main.cpp: In function 'int main()':
main.cpp:35:10: error: no match for 'operator<<' (operand types are 'std::ostream {aka std::basic_ostream<char>}' and 'A<int>::S')
cout << a.s << endl;
^
How can I overload operator<< for a substruct of a class template?