重载运算符<<用于嵌套类模板
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和朋友。我试过这个:
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;
}
};
我正在以另一种方式挖掘...
解决方法 - 在Bar
的定义中将operator<<
定义为朋友:
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。Foo<T>::Bar
可能有无限多个T
,每个也可能导致不同的类型。
编译器无法推断 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;
}
相关文章:
- 嵌套在类中时无法设置成员数据
- 无法访问嵌套类.类的使用无效
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- 如何在C++中初始化嵌套类中的2个memeber
- 如何声明特征矩阵,然后通过嵌套循环初始化它
- 在C++中搜索嵌套多映射值
- 在C++中将矢量转换为嵌套地图
- C++嵌套if语句,基本货币交换
- 在nlohmann json中,如何将嵌套对象的数组转换为嵌套结构的向量
- 嵌套的匿名命名空间
- 了解嵌套循环打印星号图案
- 如何使用boost::具有嵌套结构和最小代码更改的序列化
- 嵌套for循环C++的问题(初学者)
- 从嵌套在std::映射中的std::列表中删除元素的最佳方式
- 用C#中的并集模拟C++嵌套结构
- 部分专业化和嵌套模板
- 嵌套While循环不起作用(C++问题)
- C++-模板嵌套类的引用初始化无效
- 如何在嵌套类中正确使用友元声明?
- UE4 C++ 我无法将 JSON 嵌套值获取到 TArray