c++ - 模板类的运算符<<()

标签 c++ templates

我想重载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/

相关文章:

c++ - 为什么 unordered_set 不允许 vector 作为键?

templates - Grails:模板与 TagLib。

java - NewDirectByteBuffer 返回奇怪的值

c++ - 捕获异常时可以使用 gdb 进行回溯吗?

c++ - boost 函数组成

django - 高级 Django 模板逻辑

c++ - "multiple template parameter lists are not allowed"?

c++ - 是否可以模拟模板<auto X>?

c++ - 避免通用容器中 begin() 和 end() 函数的重复代码

c++ - ORB 未检测 opencv 2.4.9 中的关键点