c++ - 重载的 operator<< 模板不适用于 std::list,尽管它适用于 std::vector

标签 c++ templates

通过模板,我重载了 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/

相关文章:

c++ - 2 个本地服务器(C++ 上的逻辑服务器和网页的 Web 服务器)数据交换。如何?

C++ - auto 和 decltype 的替代方案

c++ - 将数据类型作为字符串放入模板参数中 - C++

c++ - "error: no viable conversion from tuple..."使用 make_tuple

c++ - boost::进程间消息队列创建时的竞争条件?

c++ - N 的阶乘,其中 N 大于 200

c++ - Visual Studio C++ 外部依赖项

c++ - 如何将 sort() 的比较参数与模板和自定义数据结构一起使用

c++ - 如何使用模板推导 std::function 的参数类型?

templates - 检查类成员是否是静态的