ezpresso
ezpresso

Reputation: 8126

Implementing a function that "plugs" into a stream

I have implemented a function that prints the memory layout of a struct/class. I would like this function to "plug" into a stream this way:

BaseStruct1 struct1;
cout << "The struct1 object is:" << endl;
cout << OutputObjectLayout(&struct1, sizeof(struct1)) << endl;

How this could be done? Thanks for any input!

Upvotes: 2

Views: 97

Answers (2)

ezpresso
ezpresso

Reputation: 8126

I finally found the answer myself here: http://my.safaribooksonline.com/book/programming/cplusplus/0596007612/streams-and-files/cplusplusckbk-chp-10-sect-3.

Here is an example of how it could be done:

First, we need to define a temporary class to do the work. The temporary structure should look something like this:

class WidthSetter {
public:
   WidthSetter (int n) : width_(n) {}
   void operator( )(ostream& os) const {os.width(width_);}
private:
   int width_;
};

The point of this behavior is that WidthSetter will be constructed by one function and used by another. The manipulator function is what will construct it, and it should look like this:

WidthSetter setWidth(int n) {
   return(WidthSetter(n));   // Return the initialized object
}

All this does is return a WidthSetter object that was initialized with the integer value. This is the manipulator that we will use in line with operator<

myostream << setWidth(20) << "banana";

But this alone is not enough, because if setWidth just returns a WidthSetter object, operator<< won't know what to do with it. We have to overload operator<< so it knows how to handle a WidthSetter:

ostream& operator<<(ostream& os, const WidthSetter& ws) {
   ws(os);     // Pass the stream to the ws object
   return(os); // to do the real work
}

Upvotes: 1

Daniel A. White
Daniel A. White

Reputation: 190942

Overload the << operator.

See: http://www.java2s.com/Code/Cpp/Overload/Overloadstreamoperator.htm

Upvotes: 2

Related Questions