重载运算符<<() 用于 stl 容器
Overloading operator<<() for stl containers
我正在尝试重载 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
不起作用? 是否有任何解决方法可以解决此问题?
我已经在互联网和 SO 中搜索过,以查找是否有办法为 stl 容器重载operator<<()
。 我已经阅读了 c++ stl 容器重载<<运算符中的答案,但它没有回答我的问题。 在我看来,漂亮打印C++ STL 容器中的答案似乎很完美。
G++ 版本:g++ (Ubuntu 4.8.4-2ubuntu1~14.04.3) 4.8.4
编译命令:g++ -std=c++11
看看template <class...> class TT
.此参数用于模板,即接受任意数量类型参数的任何模板。
现在看看std::array<class T, std::size_t N>
.此模板不接受类型作为第二个参数。它接受一个整数常数。
因此,它不能是您定义的模板函数的参数,并且模板参数推导因此而失败。
至于使其工作,最简单的方法是提供一个仅接受std::array
的(模板化(重载。模板参数将是(推导的(数组参数。
template<typename T, std::size_t N>
ostream& operator<<(ostream& out, std::array<T, N> const& a)
{
out << "[ ";
for(auto x : a)
{
out << x << " ";
}
out << "]";
return out;
}
您的重载不适用于std::array
,因为它与std::array
使用的模板不匹配。 与所有其他标准容器不同,std::array
模板参数列表中有一个非类型模板参数。 它被定义为
template<typename T, std::size_t N>
struct array;
这不适用于template <template <class...> class TT, class ...T>
,因为它只使用类型,不允许非类型、std::size_t N
部分。
如果添加此重载,它应该可以工作
template <class T, std::size_t N>
ostream& operator<<(ostream& out, std::array<T, N>& c)
{
out << "[ ";
for(auto x : c)
{
out << x << " ";
}
out << "]";
return out;
}
另请注意,您不会在过载中返回out
。 这是未定义的行为,因为您告诉编译器您正在返回某些内容,但您没有这样做。
- 在C++STL中是否有Polyval(Matlab函数)等价物?
- 为什么这个运算符<重载函数对 STL 算法不可见?
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- 呼叫运营商<<临时
- 在C应用程序中运行C++(带有STL)函数
- 使用2个键的cpp-stl::优先级队列排序不正确
- 如何防止clang格式在流运算符调用之间添加换行符<<
- 在STL容器中使用模板类
- <<操作员在下面的行中工作
- 用C++中的CPerson(类)类型的对象初始化STL矢量
- 将stl字符串缩小到小于15个字符的容量
- 在为LINUX创建共享库时,如何避免STL的私有/弱副本
- 检查函数返回类型是否与STL容器类型值相同
- STL算法函数在多个一维容器上的使用
- 在STL - C++中按成绩对学生列表进行排序?
- 为什么 STL 容器适配器堆栈中的 top 返回常量引用?
- λ可以适应STL吗?
- 为什么使用 NDK 不能存在不同的 stl 实现?
- 如果我真的真的想从 STL 容器继承,并且我继承构造函数并删除新运算符,会发生什么?
- 使用map<>来自STL