gpt4 book ai didi

c++ - 为嵌套类模板重载运算符<<

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:59:44 31 4
gpt4 key购买 nike

我有以下设置:

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 和 friend 。我试过这个:

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<< 下表现良好? ?

谢谢!

最佳答案

是的,简单的方法是输入 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;
}
};

我正在用另一种方式挖掘......

关于c++ - 为嵌套类模板重载运算符<<,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18823618/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com