2012-02-27 58 views
1

我有一個調試類,我在我的代碼中使用打印各種東西。在這個類中,我重載operator()以方便輸出。我有幾個operator()打印載體。當我添加模板版本時,我遇到了編譯錯誤。任何矢量打印內容

下面是代碼:

template<class Type1> 
    inline debug& 
    operator()(const std::string& name, 
       typename std::vector<Type1>::const_iterator begin, 
       typename std::vector<Type1>::const_iterator end) 
    {  
     _stream << indent(internal) << "< " << name << " : [ "; 
     std::copy(begin, end, std::ostream_iterator<Type1>(_stream, " ")); 
     _stream << "] >" << std::endl; 

     return *this; 
    } 

而另一矢量打印功能,我有:

inline debug& 
    operator()(const std::string& name, 
      typename std::vector<uint32_t>::const_iterator begin, 
      typename std::vector<uint32_t>::const_iterator end) 
    { 
    _stream << indent(internal) << "< " << name << " : [ " << std::hex; 
    std::copy(begin, end, std::ostream_iterator<uint32_t>(_stream, " ")); 
    _stream << "] >" << std::endl; 

    return *this; 
    } 

indent()不正是它說。

這裏是編譯錯誤:

../include/debug.hh:146:3: note: template<class Type1> relix::debug& relix::debug::operator()(const string&, typename std::vector<_RealType>::const_iterator, typename std::vector<_RealType>::const_iterator) 
../include/debug.hh:146:3: note: template argument deduction/substitution failed: 
assembler.cc:78:64: note: couldn't deduce template parameter ‘Type1’ 

這裏是assembler.cc:78:

log(D_C(tl._tokens), tl._tokens.begin(), tl._tokens.end()); 

D_C()是取代預處理宏提取變量的名稱和_tokens是的std::vectortoken,其中token有一個超載operator<<()

+2

請創建演示問題的儘可能小的程序,然後在您的問題中複製粘貼整個程序。 http://sscce.org/。 – 2012-02-27 15:01:12

回答

2

的問題是隻有模板:

template<class Type1> 
inline debug& 
operator()(const std::string& name, 
      typename std::vector<Type1>::const_iterator begin, 
      typename std::vector<Type1>::const_iterator end) 
{  
// ... 

的這裏的問題是,Type1不能由編譯器推斷。考慮實際推導類型需要做什麼:編譯器將不得不實例化std::vector全部可能的類型,包括任何可能的實例化std::vector以確定函數的參數是否匹配。

最簡單的解決方法是從簽名中的明確要求下降vector並將其轉換爲:

template<class Iterator> 
inline debug& 
operator()(const std::string& name, 
      Iterator begin, 
      Iterator end) 
{  
// ... 

現在的類型,可以推導出平凡,無論參數的功能。

+0

那麼是否有辦法爲特定類型的迭代器(即std :: vector :: const_iterator)專門化模板,還是編譯器會自動將它匹配到第二個函數? – nerozehl 2012-02-27 15:10:08

+0

@nerozehl:你可以按照你陳述的方式(但沒有'typename')來進行特殊化,但是對於函數來說,它通常最好是* override *:'inline debug&operator()(const std :: string&name, std :: vector :: const_iterator begin,...'請注意,在* specialization *中沒有*類型來推導*,你告訴它確切的類型是什麼 – 2012-02-27 15:25:49

+0

我試過你的方法,但我得到了一個迴轉來自/home/nerozehl/local/lib/gcc/x86_64-unknown-linux-gnu/4.7.0/../../../../include/c++/4.7.0/iterator:66的錯誤: 0,關於沒有已知的轉換我可以輸出的類型使用 – nerozehl 2012-02-27 15:33:47