我想重载operator <<()
对于我自己的类(class),这也是一个模板。我的类(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<<()
正确以便编译器找到正确的匹配项?
最佳答案
如果要为类t_zstring定义<<运算符,我觉得这样写比较容易:
template<typename OS, typename RepType>
OS& operator<<(OS &os, t_zstring<RepType> const &s )
{
return os << s.c_str();
}
关于c++ - 模板类的运算符<<(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3276308/