首页 > 解决方案 > C++ 使用 ostream_iterator 解决 STL 容器的 ostream 运算符<< 重载

问题描述

我已经为 std::vector 编写了 ostream operator<< 的重载。它基于在这里找到的解决方案,在stackoverflow的深处:

template <typename T, typename AllocT>
std::ostream& operator<< (std::ostream& out, const std::vector<T, AllocT>& v) {
    if (!v.empty()) {
        out << "[";
        std::copy(v.begin(), v.end(), std::ostream_iterator<T>(out, ", "));
        out << "\b\b]";
    }
    return out;
}

对于简单的类型,一切似乎都可以正常工作:

auto vt = std::vector<int>({ 1, 2, 4 });
std::cout << vt;

>> [1, 2, 4]

但是,每当我尝试进行递归时:

auto vt = std::vector<std::vector<int>>({ {1, 2}, {3, 4} });
std::cout << vt;

>> error C2679: binary '<<': no operator found which takes a right-hand operand of type 'const _Ty' (or there is no acceptable conversion) 
            with
            [
                _Ty=std::vector<int,std::allocator<int>>
            ]
... while trying to match the argument list '(std::basic_ostream<char,std::char_traits<char>>, const _Ty)'...
... while compiling class template member function 'std::ostream_iterator<T,char,std::char_traits<char>>
   &std::ostream_iterator<T,char,std::char_traits<char>>::operator =(const _Ty &)'
            with
            [
                T=std::vector<int,std::allocator<int>>,
                _Ty=std::vector<int,std::allocator<int>>
            ]

这很奇怪,因为编译器似乎被困在解决重载问题上operator<<(std::basic_ostream<char,std::char_traits<char>>, const std::vector<int,std::allocator<int>>&),这(理论上)我们应该能够产生。

据我了解,std::ostream实际上是一样的std::basic_ostream<char>,所以这里应该没有任何问题。或者可能是 constness 出了点问题,尽管我也看不出真正的问题。

标签: c++templatesc++17

解决方案


推荐阅读