2010-07-18 103 views
1

我想爲我自己的類也重載operator <<(),這也是一個模板。我班如下:operator <<()for template class

template< 
    typename RefCountType, 
    typename TraitsType = std::char_traits<char>, 
    typename Allocator = std::allocator<typename TraitsType::char_type> 
> 
class rep { 
    // ... 
}; 

template<typename RepType> 
class t_zstring { 
    // ... 
}; 

operator<<()的代碼是:

template< 
    typename CharType, 
    typename TraitsType, 
    typename Allocator, 
    typename RefCountType, 
    template<class,class,class> class RepType 
> 
inline std::basic_ostream<CharType,TraitsType>& 
operator<<(std::basic_ostream<CharType,TraitsType> &os, 
      t_zstring< RepType<RefCountType,TraitsType,Allocator> > const &s) { 
    return os << s.c_str(); 
} 

模板代碼編譯就好了;然而,當我嘗試使用它像(與省略掉了my_ref_count類的代碼):

typedef rep<my_ref_count> my_rep; 
typedef t_zstring<my_rep> zstring; 
zstring z; 
cout << z; // ztest.cpp, line 201 

我得到(使用G ++ 4.2.1):

ztest.cpp:201: error: no match for ‘operator<<’ in ‘std::cout << z1’ 

我如何申報我operator<<()正確,所以編譯器會找到正確的匹配?

+0

不應該'運營商<<()'只需要一個參數? – 2010-07-18 16:36:31

+1

@klez - no,因爲'operator <<'是一個自由函數,所以它需要兩個參數。 – 2010-07-18 16:39:07

+0

@R Samuel Klatchko,完美,現在我更加確定我不瞭解C++:D – 2010-07-18 16:42:11

回答

0

如果要定義< <運營商級t_zstring,我認爲這是比較容易寫:

template<typename OS, typename RepType> 
OS& operator<<(OS &os, t_zstring<RepType> const &s) 
{ 
    return os << s.c_str(); 
} 
+0

除了沒有限制操作系統的類型爲std :: basic_ostream – 2010-07-21 16:41:50

+0

是的,你是對的 正如你所建議的g ++ 4.2.1可能會被打破,我認爲一個更容易的聲明可能會解決這個問題。 畢竟,將操作系統限制到std :: basic_ostream並不總是必要的。 – 2010-07-21 22:08:47

相關問題