如何正确重载运算符<<对于具有嵌套私有类集合的类?
How to properly overload the operator<< for a class with a collection of nested private classes?
我想为我的模板类实现operator<<
,以便它可以将它包含的所有元素打印到给定的std::ostream&
。问题是,我似乎无法让它识别我定义的函数。
error: no match for 'operator<<' (operand types are 'std::ostream {aka std::basic_ostream<char>}' and 'Outer<int>::Inner')
os << inner << ", ";
~~~^~~~~~~~
理想情况下,我不想让函数内联定义,但我甚至不能让它内联工作。在下面的代码中,您可以看到我已经注释掉了在类声明之外定义它的尝试。它会产生与上面相同的错误。
这个问题建议将操作符作为类的友元。我已经试过了所有我能想到的方法,但还是不管用。
代码:
#include <iostream>
template<class T>
class Outer {
class Inner {
T item;
template<class T_>
friend std::ostream& operator<<(std::ostream& os, const typename Outer<T_>::Inner& inner) {
os << inner.item;
return os;
}
template<class T_>
friend std::ostream& operator<<(std::ostream& os, const Outer<T_> outer);
};
std::vector<Inner> inner_items;
template<class T_>
friend std::ostream& operator<<(std::ostream& os, const Outer<T_> outer);
template<class T_>
friend std::ostream& operator<<(std::ostream& os, const typename Outer<T_>::Inner& bar);
};
/*template<class T>
std::ostream& operator<<(std::ostream& os, const typename Outer<T>::Inner& bar) {
os << inner.item;
return os;
}*/
template<class T>
std::ostream& operator<<(std::ostream& os, const Outer<T> outer) {
for (typename Outer<T>::Inner inner : outer.inner_items) {
os << inner << ", ";
}
return os;
}
int main()
{
Outer<int> outer;
std::cout << outer;
}
是否不为嵌套类型模板的输出操作符:
#include <iostream>
#include <vector>
template<class T>
class Outer {
class Inner {
T item;
friend std::ostream& operator<<(std::ostream& os, typename Outer<T>::Inner const& inner) {
os << inner.item;
return os;
}
friend std::ostream& operator<<(std::ostream& os, const Outer<T> outer);
};
template <typename T_>
friend std::ostream& operator<< (std::ostream&, Outer<T_> const&);
std::vector<Inner> inner_items;
};
template<class T>
std::ostream& operator<<(std::ostream& os, Outer<T> const& outer) {
for (typename Outer<T>::Inner const& inner : outer.inner_items) {
os << inner << ", ";
}
return os;
}
int main()
{
Outer<int> outer;
std::cout << outer;
}
有少量的const&
和必要的friend
声明。
您不需要(也不想)在Inner
中进行模板化,只需使用类型:
class Outer {
class Inner {
T item;
friend std::ostream& operator<<(std::ostream& os, const Inner& inner) {
os << inner.item;
return os;
}
// ...
你上面写的失败了,因为你在Outer<T>::Inner
中定义了一个自由函数,即operator<<(..)
。第二个形参是Outer<T_>::Inner
,编译器不能从Inner
转换到定义它的类型。
相关文章:
- 处理多个异常集合的C++方法
- 给定n个元素的m个集合.在C++中找到出现在最大集合数中的元素
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- 如何将ampl中的集合表示为c++中的向量
- 呼叫运营商<<临时
- 检查值是否在集合p1和p2中,但不在p3中
- 带过滤器的现代迭代c++集合
- 如何将结构插入到集合中并打印集合的成员
- 集合上的输出迭代器:assign和increment迭代器
- 如何将函数集合传递给客户端类,以便将它们当作客户端类本身的成员使用
- 实现一个在集合上迭代的模板函数
- 如何防止clang格式在流运算符调用之间添加换行符<<
- 尝试使用集合函数时出现分段错误
- 互斥指针的集合
- <<操作员在下面的行中工作
- c++找不到具有相同哈希的无序集合元素
- python集合的C++等价物是什么.计数器
- 如何在C++中递归地按相反顺序打印集合
- Python 集合.计数器,如何避免重复查找
- 如何写向量的无序向量集,即unordered_set<向量<向量<int>>集合?