C++ 过载操作员<&书信电报;对于嵌套类模板
我有以下设置:C++ 过载操作员<&书信电报;对于嵌套类模板,c++,templates,operator-overloading,friend,nested-class,C++,Templates,Operator Overloading,Friend,Nested Class,我有以下设置: template< class T > struct Foo { struct Bar { Bar ( const T &t ) : otherT_( t ) {} T otherT_; }; Foo ( const T &t ) : myT_( t ) {} T myT_; }; 模板 结构Foo{ 结构条{ Bar(const T&T):其他T(T){ T其他T_; }; Foo(const T&T):my
template< class T >
struct Foo {
struct Bar {
Bar ( const T &t ) : otherT_( t ) {}
T otherT_;
};
Foo ( const T &t ) : myT_( t ) {}
T myT_;
};
模板
结构Foo{
结构条{
Bar(const T&T):其他T(T){
T其他T_;
};
Foo(const T&T):myT_u(T){}
T myT_2;;
};
现在,我想将Foo::Bar的实例流化为std::cout和friends。我试过这个:
template< class T >
std::ostream& operator<< ( std::ostream &os,
const typename Foo< T >::Bar &bar ) {
os << "<bar: " << bar.otherT_ << ">";
return os;
}
模板
std::ostream和操作员::Bar和Bar){
os::Bar(7);
std::cout是的,简单的方法是放置运算符变通方法-定义运算符编译器无法推导出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;
}
#包括
使用名称空间std;
模板
结构Foo{
结构条{
Bar(const T&T):其他T(T){
T其他T_;
friend std::ostream&运营商foo(5);
Foo:Bar(7);
std::cout Copy/paste?@KerrekSB因此答案是不可能简单地编写std::cout@KerrekSB。我不确定我是否遵循引用的答案。他的错误原因很简单:Foo::Bar
中的T
是一个非推断上下文,请参见§14.8.2.5/5。正如其他人所指出的,让函数成为朋友是可行的(因为生成的函数不是模板,所以不需要类型推断)。@JamesKanze:“非推断上下文”这是两个问题的共同原因。问题总是在于,如果X
@KerrekSB给定X
,思考你可以解决Foo::Bar=X
,这不是你能否解决某件事的问题,而是标准上说你不允许尝试的事实。(事实上,这个问题是可以解决的,但被标准委员会认为对于当前的编译器技术来说是复杂的。):)仍然在尝试另一种方法:)我认为模板别名可能有助于推断,但让我直截了当
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;
}
};
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_;
};
#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;
}