通过模板,我重载了 operator<< 以便它输出容器的所有元素:
template<typename T, template<typename> typename C>
ostream& operator<<(ostream& o, const C<T>& con) { for (const T& e : con) o << e; return o; }
它可以与 std::vector
一起使用s,但是当我尝试将它应用于 std::list
时它会产生一条错误消息:
error: no match for ‘operator<<’ (operand types are ‘std::ostream {aka std::basic_ostream}’ and ‘std::__cxx11::list’) cout << li;
这是我的代码摘录(在 GCC 5.2.1、Ubuntu 15.10 上编译):
#include "../Qualquer/std_lib_facilities.h"
struct Item {
string name;
int id;
double value;
Item(){};
Item(string n, int i, double v):
name{n}, id{i}, value{v} {}
};
istream& operator>>(istream& is, Item& i) { return is >> i.name >> i.id >> i.value; }
ostream& operator<<(ostream& o, const Item& it) { return o << it.name << '\t' << it.id << '\t' << it.value << '\n'; }
template<typename T, template<typename> typename C>
ostream& operator<<(ostream& o, const C<T>& con) { for (const T& e : con) o << e; return o; }
int main()
{
ifstream inp {"../Qualquer/items.txt"};
if(!inp) error("No connection to the items.txt file\n");
istream_iterator<Item> ii {inp};
istream_iterator<Item> end;
vector<Item>vi {ii, end};
//cout << vi;//this works OK
list<Item>li {ii, end};
cout << li;//this causes the error
}
但是,当我专门为std::list
写模板的时候,它工作正常:
template<typename T>
ostream& operator<<(ostream& o, const list<T>& con) { for (auto first = con.begin(); first != con.end(); ++first) o << *first; return o; }
为什么 ostream& operator<<(ostream& o, const C<T>& con)
模板结果不适用于 std::list
?
最佳答案
template<typename T, template<typename> typename C>
ostream& operator<<(ostream& o, const C<T>& con) { for (const T& e : con) o << e; return o; }
为什么这么复杂?您只需要键入名称 T
才能在 for 循环中使用它。您也可以通过 C::value_type
获取它,或者只使用 auto
关键字:
template<typename C>
ostream& operator<<(ostream& o, const C& con)
{
for (const typename C::value_type& e : con) o << e; return o;
}
template<typename C>
ostream& operator<<(ostream& o, const C& con)
{
for (auto& e : con) o << e; return o;
}
关于c++ - 重载的 operator<< 模板不适用于 std::list,尽管它适用于 std::vector,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41331806/