2015-06-18 41 views
0

我有一個模板方法,使運算符< <過載。我需要在調用某個類的方法時調用該運算符。但是,當我嘗試它給我一些編譯錯誤。來自不同類的調用模板方法。

這是命名爲BTreeLeave

bool BTreeLeave::burn() { 
    csv::WriterStream os("products.txt", std::ios_base::out); 
    os.set_delimiter(','); 
    if (os.is_open()) { 

     os << 1693 << NEWLINE; 
     os << 15 << 16 << 17 << 20 << NEWLINE; 
     os << "s" << "i" << "f" << NEWLINE; 
     os << 2 << NEWLINE; 
     os << "+" << NEWLINE; 
     os << "0" << NEWLINE; 
    } 

具體類的方法模板函數是這樣一個

template<typename T> 
typename csv::WriterStream& operator << (typename csv::WriterStream& ostm, const T& val) 
{  
    if(!ostm.get_after_newline()) 
     ostm.get_ofstream() << ostm.get_delimiter();  
    ostm.get_ofstream() << val;  
    ostm.set_after_newline(false);  
    return ostm; 
} 
template<> 
inline csv::WriterStream& operator << (typename csv::WriterStream& ostm, const char& val) 
{ 
    if(val==NEWLINE) 
    { 
     ostm.get_ofstream() << NEWLINE; 
      ostm.set_after_newline(true); 
    }  
    else 
     ostm.get_ofstream() << val;  
    return ostm; 
} 

我得到的錯誤是 「CSV :: WriterStream」不是來源於'std :: basic_ostream' 和 「不匹配'操作符< <'(操作數類型爲'csv :: WriterStream'和'int')」

如果我嘗試從主函數中調用< <運算符,請執行以下操作。我究竟做錯了什麼 ?

+1

你在哪裏有你的輸出運算符重載定義的?他們在全球範圍內?不在任何類或名稱空間中?你是否可以請嘗試創建一個[最小,完整和可驗證示例](http://stackoverflow.com/help/mcve)向我們展示? –

回答

0

你試試下面界定及

template<typename T> 
typename csv::WriterStream& operator << (typename csv::WriterStream& ostm, T val) 
{  
    if(!ostm.get_after_newline()) 
     ostm.get_ofstream() << ostm.get_delimiter();  
    ostm.get_ofstream() << val;  
    ostm.set_after_newline(false);  
    return ostm; 
}