Pisanie manipulatora dla niestandardowej klasy strumienia
Napisałem niestandardową klasę strumienia, która wyświetla wcięty tekst i ma manipulatory, które mogą zmieniać poziom wcięcia. Cała praca wcięcia jest zaimplementowana w niestandardowej klasie bufora strumienia, która jest używana przez klasę strumienia. Bufor działa (tzn. Tekst jest wcięty na wyjściu), ale nie mogę zmusić moich manipulatorów do działania. Czytałem w wielu miejscach, jak ostream (który moja klasa rozszerza) przeciąża operatora << w ten sposób:
ostream& ostream::operator << ( ostream& (*op)(ostream&))
{
// call the function passed as parameter with this stream as the argument
return (*op)(*this);
}
Co oznacza, że może przyjąć funkcję jako parametr. Dlaczego więc nie są rozpoznawane moje funkcje „wcięcia” lub „deindentu”? Jestem pewien, że muszę zrobić przeciążenie operatora <<, ale czy nie powinienem tego robić? Zobacz poniżej mój kod:
#include <iostream>
#include <streambuf>
#include <locale>
#include <cstdio>
using namespace std;
class indentbuf: public streambuf {
public:
indentbuf(streambuf* sbuf): m_sbuf(sbuf), m_indent(4), m_need(true) {}
int indent() const { return m_indent; }
void indent() { m_indent+=4; }
void deindent() { if(m_indent >= 4) m_indent-= 4; }
protected:
virtual int_type overflow(int_type c) {
if (traits_type::eq_int_type(c, traits_type::eof()))
return m_sbuf->sputc(c);
if (m_need)
{
fill_n(ostreambuf_iterator<char>(m_sbuf), m_indent, ' ');
m_need = false;
}
if (traits_type::eq_int_type(m_sbuf->sputc(c), traits_type::eof()))
return traits_type::eof();
if (traits_type::eq_int_type(c, traits_type::to_char_type('\n')))
m_need = true;
return traits_type::not_eof(c);
}
streambuf* m_sbuf;
int m_indent;
bool m_need;
};
class IndentStream : public ostream {
public:
IndentStream(ostream &os) : ib(os.rdbuf()), ostream(&ib){};
ostream& indent(ostream& stream) {
ib.indent();
return stream;
}
ostream& deindent(ostream& stream) {
ib.deindent();
return stream;
}
private:
indentbuf ib;
};
int main()
{
IndentStream is(cout);
is << "31 hexadecimal: " << hex << 31 << endl;
is << "31 hexadecimal: " << hex << 31 << endl;
is << "31 hexadecimal: " << hex << 31 << deindent << endl;
return 0;
}
Dzięki!