簡體   English   中英

重載的operator <<模板不適用於std :: list,盡管適用於std :: vector

[英]The overloaded operator<< template doesn't work for std::list, although it does for std::vector

通過模板,我重載了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一起正常工作,但是當我嘗試將其應用於std::list時會產生錯誤消息:

錯誤:與'operator <<'不匹配(操作數類型為'std :: ostream {aka std :: basic_ostream}'和'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; }

為什么這么復雜? 您只需要在您的for循環中使用名稱T即可。 您也可以通過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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM