Search code examples
c++templatesoperator-overloadingfriendnested-class

Overload operator<< for nested class template


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!


Solution

  • Yep, the easy way is to put operator<< inside Bar:

    struct Bar {
      Bar ( const T &t ) : otherT_( t ) {}
    
      T otherT_;
    
      friend std::ostream& operator<< ( std::ostream &os, const Bar &bar ) 
      {
        os << "<bar: " << bar.otherT_ << ">";
        return os;
      }
    };
    

    I am digging the other way ...