I have the following setup:
template< class T >
struct Foo {
struct Bar {
Bar ( const T &t ) : otherT_( t ) {}
T otherT_;
};
Foo ( const T &t ) : myT_( t ) {}
T myT_;
};
Now, I want to make instances of Foo< T >::Bar
streamable to std::cout and friends. I tried this:
template< class T >
std::ostream& operator<< ( std::ostream &os,
const typename Foo< T >::Bar &bar ) {
os << "<bar: " << bar.otherT_ << ">";
return os;
}
But the following code does not compile:
Foo< int > foo( 5 );
Foo< int >::Bar bar( 7 );
std::cout << bar << std::endl;
I guess that the compiler is not able to deduce the type T
or something. Is there a way to make such instances of the nested class behave well with operator<<
?
Thank you!
The compiler cannot deduce T, however, when you make it a friend it finds it via ADL.
I've modified the code to the following:
Workaround - define
operator<<
as a friend insideBar
's definition:The problem with your approach is, as KerrekSB said in comments, that T could not be deduced. There are possibly infinitely many
T
forFoo<T>::Bar
, each of which could result in a different type, too.Yep, the easy way is to put
operator<<
insideBar
:I am digging the other way ...