【发布时间】:2018-01-01 18:10:51
【问题描述】:
我正在尝试为 stl 容器(例如 vector、list、array)重载 operator<<()(即插入器运算符)(即任何支持基于范围的 for 循环并且其 value_type 也operator<<() 有过载)。我写了以下模板函数
template <template <class...> class TT, class ...T>
ostream& operator<<(ostream& out, const TT<T...>& c)
{
out << "[ ";
for(auto x : c)
{
out << x << " ";
}
out << "]";
}
它适用于vector 和list。但是当我尝试为array调用它时会出错
int main()
{
vector<int> v{1, 2, 3};
list<double> ld = {1.2, 2.5, 3.3};
array<int, 3> aa = {1, 2, 3};
cout << v << endl; // okay
cout << ld << endl; // okay
cout << aa << endl; // error: cannot bind ‘std::ostream {aka std::basic_ostream<char>}’ lvalue to ‘std::basic_ostream<char>&&’
// cout << aa << endl;
// ^
}
为什么它不适用于array?
有什么办法可以解决这个问题吗?
我在互联网上进行了搜索,以查找是否有办法为 stl 容器重载 operator<<()。
我已经阅读了overloading << operator for c++ stl containers 中的答案,但它没有回答我的问题。
Pretty-print C++ STL containers 中的答案对我来说似乎很复杂。
g++ 版本:
g++ (Ubuntu 4.8.4-2ubuntu1~14.04.3) 4.8.4
编译命令:
g++ -std=c++11
【问题讨论】:
-
尽管没有返回 void,但您的运算符未能返回值。
-
好吧,你要么从你链接的问题中得到复杂的答案(需要复杂性),要么为不同的容器编写不同的重载。毕竟只有少数几个容器。
标签: c++ c++11 templates stl operator-overloading