我有以下设置:
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 >::Bar
的实例能够输出到 std::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<<
良好地配合?
谢谢!
Foo<T>::Bar
中的T
是无法推导的上下文,详见 §14.8.2.5/5。正如其他人所指出的那样,将该函数设置为友元是可行的(因为生成的函数不是一个模板,所以不需要进行类型推导)。 - James KanzeFoo<T>::Bar = X
中的T
来得到X
的想法上。 - Kerrek SBtemplate <> struct Foo<int> { typedef int Bar; };
。突然间你破坏了std::cout << 10;
... - Kerrek SB