5

我有以下设置:

template< class T >
struct Foo {

  struct Bar {
    Bar ( const T &t ) : otherT_( t ) {}

    T otherT_;
  };

  Foo ( const T &t ) : myT_( t ) {}

  T myT_;
};

现在,我想让Foo< T >::Barstd::cout 和朋友可以流式传输实例。我试过这个:

template< class T >
std::ostream& operator<< ( std::ostream &os, 
                           const typename Foo< T >::Bar &bar ) {
  os << "<bar: " << bar.otherT_ << ">";
  return os;
}

但以下代码无法编译:

  Foo< int > foo( 5 );
  Foo< int >::Bar bar( 7 );

  std::cout << bar << std::endl;

我猜编译器无法推断出类型T或其他东西。有没有办法让嵌套类的此类实例表现良好operator<<

谢谢!

4

3 回答 3

10

是的,简单的方法是放在operator<<里面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;
  }
};

我正在挖另一个方向...

于 2013-09-16T08:42:05.733 回答
3

解决方法 -operator<<在 的定义中定义为朋友Bar

template< class T >
struct Foo {

  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;
    }

  };

  Foo ( const T &t ) : myT_( t ) {}

  T myT_;
};

正如KerrekSB 在评论中所说,您的方法的问题是无法推断出 T 。可能有无数个Tfor Foo<T>::Bar,每一个也可能导致不同的类型。

于 2013-09-16T08:42:31.473 回答
1

编译器无法推断出 T,但是,当您将其设为朋友时,它会通过 ADL 找到它。

我已将代码修改为以下内容:

#include <iostream>
using namespace std;

template< class T >
struct Foo {

struct Bar {
Bar ( const T &t ) : otherT_( t ) {}

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

Foo ( const T &t ) : myT_( t ) {}


T myT_;
};

int main() {
Foo< int > foo( 5 );
Foo< int >::Bar bar( 7 );

std::cout << bar << std::endl;
return 0;
}
于 2013-09-16T08:48:56.880 回答