alanlittle
alanlittle

Reputation: 470

Custom output buffer for CGI program, operator overloading

I'm working on a CGI application, which needs to send response headers, including Content-Length, before the body, but of course this is unknown until the body is fully formed. I could just use a string and concatenate as I go, but I like using the << operator as with cout, so I created this little class:

#include <iostream>

using namespace std;

class outbuf {
    public:
        void operator<<(const char *str) {
            this->buffer+= str;
        }

        void operator<<(const string &str) {
            this->buffer+= str;
        }

        void obsend() {
            cout << this->buffer;
            this->buffer.clear();
        }

    private:
        string buffer;
};

int main(int argc, char **argv, char** envp) {
    outbuf cbout;
    string s = " of the output buffer.";

    cbout << "This is ";
    cbout << "a test" << " ...";
    cbout << s;

    cbout.obsend();

    return 0;
}

The problem comes with cbout << "a test" << " ..."; On the second operator, the compiler complains invalid operands of types 'void' and 'const char [5]' to binary 'operator<<' I understand the error, but not sure what to do about it. Is there a better way to accomplish what I'm trying to do? This article looked promising, but I'm not able to understand some of what he's talking about, and it doesn't appear to exactly fit what I'm trying to do.

Upvotes: 0

Views: 32

Answers (1)

Sam Varshavchik
Sam Varshavchik

Reputation: 118352

Your operator<< overload should simply return a reference to itself:

outbuf &operator<<(const char *str) {

// ...

    return *this;
}

So now the result of the first << operator is the same object, against which the second, chained, << operator will happily use.

Change all your << operators to work this way.

Upvotes: 1

Related Questions