我想爲我自己的類也重載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<<()
正確,所以編譯器會找到正確的匹配?
不應該'運營商<<()'只需要一個參數? – 2010-07-18 16:36:31
@klez - no,因爲'operator <<'是一個自由函數,所以它需要兩個參數。 – 2010-07-18 16:39:07
@R Samuel Klatchko,完美,現在我更加確定我不瞭解C++:D – 2010-07-18 16:42:11