在从"ostream"派生的类中覆盖"operator <<"的问题

2 c++

我想基于"ostream"创建一个类,它执行一些自动格式化以生成逗号或制表符分隔值文件.我的想法是覆盖"operator <<",让它在每个值之前插入一个分隔符(除了行的开头和结尾),并在写入之前引用字符串.在重写的"operator <<"方法中,我想调用基类的方法,但我不能让它正常工作.

这是一个例子(用g ++ 4.3.3编译):

#include <iostream>
#include <ostream>
#include <string>

using namespace std;

class MyStream: public ostream
{
public:
  MyStream(ostream& out): ostream(out.rdbuf()) {}

  template <typename T> MyStream& operator<<(T value)
  {
    ostream::operator<<('+');
    ostream::operator<<(value);
    ostream::operator<<('+');
    return *this;
  }
};

template<> MyStream& MyStream::operator<< <string>(string value)
{
  ostream::operator<<('*');
  ostream::write(value.c_str(), value.size()); // ostream::operator<<(value);
  ostream::operator<<('*');
  return *this;
}

int main()
{
  MyStream mystr(cout);
  mystr << 10;
  cout << endl;
  mystr << "foo";
  cout << endl;
  mystr << string("test");
  cout << endl;
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

两个"operator <<"方法(模板和特化)用于处理字符串的方式与其他方法不同.但:

  1. 字符('+'/'*')打印为数字而不是字符.
  2. C-String"foo"打印为内存地址(我认为).
  3. 如果"注释"行与注释部分交换,编译器会抱怨"没有匹配函数来调用'MyStream :: operator <<(std :: string&)'",即使我认为我明确地调用了基类方法.

我究竟做错了什么?任何帮助非常感谢.

Joh*_*itb 5

operator<<打印字符串和字符的重载是自由函数.但是当您强制调用成员函数时,您将强制它们转换为声明的成员函数的一个候选者ostream.因为'*',它可能会使用int重载,因为"foo"它可能会使用const void*重载.

我不会继承ostream,而是将其存储ostream为引用成员,然后从您委托operator<<给它.我也不会成为operator<<一个成员,而是一个自由的功能模板,而不是专门的,但重载operator<<两者std::stringchar const*.