Operator << for inner class of template class
I want to implement operator <<
that will print the contents of the inner class of the template class i.e. X<T>::Y
... It is quite possible to add any ads friend
. How to do it?
Here is a complete example of what I want to compile in C ++ 11:
#include <iostream> template <typename T> class X { public: X(T d): y(d) {} private: class Y { public: Y(T d): data(d) {} private: T data; template <typename U> friend std::ostream &operator <<(std::ostream &os, const typename X<U>::Y &y); }; Y y; template <typename U> friend std::ostream &operator <<(std::ostream &os, const X<U> &x); }; // This operator is not detected by the operator below template <typename U> std::ostream &operator <<(std::ostream &os, const typename X<U>::Y &y) { os << "Y(" << y.data << ")"; return os; } template <typename U> std::ostream &operator <<(std::ostream &os, const X<U> &x) { os << "X " << x.y; return os; } int main() { std::cout << X<int>(1); return 0; }
Compiler error:
error: no match for 'operator<<' (operand types are 'std::basic_ostream<char>' and 'const X<int>::Y') os << "X " << x.y; ^
source share
This does not work because it typename X<U>::Y
is a dependent type. If you want to print eg. a int
if the compiler just checks all possible types for U
(there are infinitely many due to recursion) to check if the typename X<U>::Y
result is int
(consider specialization!)? Therefore, the only possibility is to implement the function directly in the friend statement:
class Y { public: Y(T d): data(d) {} private: T data; friend std::ostream &operator <<(std::ostream &os, Y const& y) { os << "Y(" << y.data << ")"; return os; } };
source share