operator<< dla zagnieżdzonych kontenerów

0

Mam poniższy kod:

#include <iostream>
#include <fstream>
#include <vector>
#include <map>
#include <string>
#include <assert.h>

using Value = std::string;
using Row = std::vector<Value>;
using Table = std::vector<Row>;

std::ostream& operator << (std::ostream& output, Table& table) {
    for (const auto& row : table) {
        output << row << "\n";
    }
    return output;
}
std::ostream& operator << (std::ostream& output, Row& row) {
    for (const auto& value : row) {
        output << value<< "|";
    }
    return output;
}

int main() {
    Table table {
         {"a", "b", "c"}
    };
    std::ofstream o;
    o.open("asd");
    assert(o.is_open());
    o << table;
}

z polecenia:
g++ --std=c++11 ./Reader.cpp
Daje błąd:

./Reader.cpp:14:19: error: cannot bind ‘std::ostream {aka std::basic_ostream<char>}’ lvalue to ‘std::basic_ostream<char>&&’
output << row << "\n";
^
In file included from /usr/include/c++/4.8.2/iostream:39:0,
from ./Reader.cpp:1:
/usr/include/c++/4.8.2/ostream:602:5: error: initializing argument 1 of ‘std::basic_ostream<_CharT, _Traits>& std::operator<<(std::basic_ostream<_CharT, _Traits>&&, const _Tp&) [with _CharT = char; _Traits = std::char_traits<char>; _Tp = std::vector<std::basic_string<char> >]’
operator<<(basic_ostream<_CharT, _Traits>&& __os, const _Tp& __x)

wersja kompilatora:

g++ --version
g++ (GCC) 4.8.5 20150623 (Red Hat 4.8.5-44)
Copyright (C) 2015 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

co jest tutaj źle ?

3
  1. zła kolejność (przeładowanie dla Row jest niewidoczne w momencie kompilacji przeładowania dla Table)
  2. masz operatory << dla non-const, a przekazujesz const wartości. Przyjmuj const referencje.

https://wandbox.org/permlink/j2KgC0w8C9Ilj1PC

0

Dzięki, pomogło ;)

1 użytkowników online, w tym zalogowanych: 0, gości: 1