Domanda

Sono stato googling in giro e non riesco proprio a trovare una risposta semplice a questa. E dovrebbe essere semplice, come lo STL è generalmente.

voglio definire MyOStream che eredita pubblicamente da std :: ostream. Diciamo che voglio chiamare foo () ogni volta che qualcosa è scritto nel mio flusso.

class MyOStream : public ostream {
public:
  ...
private:
   void foo() { ... }
}

Mi rendo conto che l'interfaccia pubblica di ostream è non virtuale, così come può essere fatto? Voglio clienti di essere in grado di utilizzare sia l'operatore << e write () e put () su MyOStream e hanno utilizzare la capacità estesa della mia classe.

È stato utile?

Soluzione

Non è una domanda semplice, purtroppo. Le classi si dovrebbe derivare da sono le classi basic_, come basic_ostream. Tuttavia, la derivazione da un flusso non può essere ciò che si vuole, si consiglia di derivare da un buffer di flusso, invece, e quindi utilizzare questa classe per creare un'istanza di una classe flusso esistente.

L'intera area è complessa, ma v'è un eccellente libro su di esso standard C ++ iostreams e locali , che vi consiglio di dare un'occhiata alla prima di andare avanti.

Altri suggerimenti

I girava la testa intorno a come fare la stessa cosa e ho scoperto che non è in realtà così difficile. Fondamentalmente solo sottoclasse l'ostream e gli oggetti streambuf, e costruire l'ostream con se stesso come tampone. il trabocco virtuale () da std :: streambuf verrà chiamato per ogni carattere inviato al flusso. Per adattare il tuo esempio ho appena fatto una funzione foo () e lo ha chiamato.

struct Bar : std::ostream, std::streambuf
{
    Bar() : std::ostream(this) {}

    int overflow(int c)
    {
        foo(c);
        return 0;
    }


    void foo(char c)
    {
        std::cout.put(c);

    }
};

void main()
{
    Bar b;
    b<<"Look a number: "<<std::hex<<29<<std::endl;
}

oh e ignorare il fatto che la funzione principale non è una vera e propria funzione principale. E 'in uno spazio dei nomi chiamato da altrove; p

Un altro mod di lavoro per ottenere un effetto simile è quello di utilizzare template e la composizione

class LoggedStream {
public:
  LoggedStream(ostream& _out):out(_out){}
  template<typename T>
  const LoggedStream& operator<<(const T& v) const {log();out << v;return *this;}
protected:
  virtual void log() = 0;
  ostream& out;
};

class Logger : LoggedStream {
  void log() { std::cerr << "Printing" << std::endl;}
};

int main(int,char**) {LoggedStream(std::cout) << "log" << "Three" << "times";}

Non so se questo è corretto soluzione, ma ho ereditato da std :: ostream in questo modo. Esso utilizza un buffer ereditato da std :: basic_streambuf e ottiene 64 caratteri alla volta (o meno se lavata) e li invia ad un generico putChars metodo () dove avviene il trattamento effettivo dei dati. Viene inoltre illustrato come dare i dati degli utenti.

diretta Esempio

#include <streambuf>
#include <ostream>
#include <iostream>

//#define DEBUG

class MyData
{
    //example data class, not used
};

class MyBuffer : public std::basic_streambuf<char, std::char_traits<char> >
{

public:

    inline MyBuffer(MyData data) :
    data(data)
    {
        setp(buf, buf + BUF_SIZE);
    }

protected:

    // This is called when buffer becomes full. If
    // buffer is not used, then this is called every
    // time when characters are put to stream.
    inline virtual int overflow(int c = Traits::eof())
    {
#ifdef DEBUG
        std::cout << "(over)";
#endif
        // Handle output
        putChars(pbase(), pptr());
        if (c != Traits::eof()) {
            char c2 = c;
            // Handle the one character that didn't fit to buffer
            putChars(&c2, &c2 + 1);
        }
        // This tells that buffer is empty again
        setp(buf, buf + BUF_SIZE);

        return c;
    }

    // This function is called when stream is flushed,
    // for example when std::endl is put to stream.
    inline virtual int sync(void)
    {
        // Handle output
        putChars(pbase(), pptr());
        // This tells that buffer is empty again
        setp(buf, buf + BUF_SIZE);
        return 0;
    }

private:

    // For EOF detection
    typedef std::char_traits<char> Traits;

    // Work in buffer mode. It is also possible to work without buffer.
    static const size_t BUF_SIZE = 64;
    char buf[BUF_SIZE];

    // This is the example userdata
    MyData data;

    // In this function, the characters are parsed.
    inline void putChars(const char* begin, const char* end){
#ifdef DEBUG
        std::cout << "(putChars(" << static_cast<const void*>(begin) <<
            "," << static_cast<const void*>(end) << "))";
#endif
        //just print to stdout for now
        for (const char* c = begin; c < end; c++){
            std::cout << *c;
        }
    }

};

class MyOStream : public std::basic_ostream< char, std::char_traits< char > >
{

public:

    inline MyOStream(MyData data) :
    std::basic_ostream< char, std::char_traits< char > >(&buf),
    buf(data)
    {
    }

private:

    MyBuffer buf;

};

int main(void)
{
    MyData data;
    MyOStream o(data);

    for (int i = 0; i < 8; i++)
        o << "hello world! ";

    o << std::endl;

    return 0;
}

Composizione, non l'ereditarietà. La classe contiene, "avvolge" un ostream &, e in avanti ad esso (dopo aver chiamato foo ()).

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top