2016-12-26 54 views
1

通過模板,我重載了運算符< <,以便它輸出容器的所有元素:重載運算符<<模板不適用於std :: list,雖然它適用於std :: vector

template<typename T, template<typename> typename C> 
ostream& operator<<(ostream& o, const C<T>& con) { for (const T& e : con) o << e; return o; } 

它的工作原理與OK 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

+3

據我可以看到你的模板運營商採用容器,其只需要一個模板參數'模板類型名稱C',都會因爲'的std :: vector'和'std :: list'不應該匹配 –

+1

這是Bjarne的教學標題,對嗎?他有一個'template class Vector'和一個'#define vector vector'。 @ W.F。 –

+0

@ T.C。是的,頭文件是Bjarne在他的網站上的教學標題。 – Jarisleif

回答

2
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; 
} 
相關問題