过载运算符<<用于嵌套的类模板 [英] Overload operator<< for nested class template
本文介绍了过载运算符<<用于嵌套的类模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下设置:
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和朋友.我试过了:
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;
我猜编译器无法推断类型T
或其他内容.有没有办法使operator<<
这样的嵌套类实例表现良好?
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<<
?
谢谢!
推荐答案
是的,简单的方法是将operator<<
放在Bar
中:
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 ...
这篇关于过载运算符<<用于嵌套的类模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文