gpt4 book ai didi

c++ - 为 STL 容器重载 operator<<()

转载 作者:搜寻专家 更新时间:2023-10-31 00:09:02 25 4
gpt4 key购买 nike

我正在尝试重载 operator<<() (即插入器运算符)用于 STL 容器(例如 vectorlistarray )(即任何支持基于范围的 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 << "]";
}

适用于 vectorlist .但是当我尝试为 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 ?有什么解决方法可以解决这个问题吗?

我在互联网上搜索过,所以想看看是否有办法重载 operator<<()对于 STL 容器。我已阅读 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

最佳答案

template <class...> class TT .此参数用于模板,任何接受任意数量的类型参数的模板。

现在看std::array<class T, std::size_t N> .此模板不接受 type 作为第二个参数。它接受一个整数常数。

因此它不能作为您定义的模板函数的参数,因此模板参数推导失败。

至于让它工作,最简单的方法是提供一个(模板化的)重载,它只接受 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;
}

关于c++ - 为 STL 容器重载 operator<<(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45326636/

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