I am trying to write a simple audit class that takes input via operator << and writes the audit after receiving a custom manipulator like this:
class CAudit
{
public:
//needs to be templated
CAudit& operator << ( LPCSTR data ) {
audittext << data;
return *this;
}
//attempted manipulator
static CAudit& write(CAudit& audit) {
//write contents of audittext to audit and clear it
return audit;
}
private:
std::stringstream audittext;
};
//to be used like
CAudit audit;
audit << "Data " << data << " received at " << time << CAudit::write;
I recognise that the overloaded operator in my code does not return a stream object but was wondering if it was still possible to use a manipulator like syntax. Currently the compiler is seeing the '<<' as the binary right shift operator.
Thanks for any input, Patrick
I do something very similar for tracing, but use a
stringstream
. This ensures that all 3rd partyoperator << ()
and manipulators work. I also use the desctructor instead of the customer write manipulator.This is then made available with some macros:
And the code just uses the macros
You don't need a specific write manipulator to flush the data to the log file. When the anonymous
DebugStream
object goes out of scope (once control leaves the line) the the contents are automatically written.Although I usually avoid macros in this case the use of the
if
statement means you don't have the overhead of building the trace line unless you actually require it.Returning the
ostream
via thestream()
method enables this to work for global member functions, as anonymous objects cannot be passed as non-const reference parameters.Binary shift operator and stream operator is the same operator. It is completely legal to overload operator+ for your class to write "Hello world" on std::cout (although it is a very bad idea). The same way C++ standard authors decided to overload operator<< for streams as writing to the stream.
You didn't write clearly what is your problem. My guess is compilation error. The best thing in this case is to quote the error message. If I am right, the problem is, that you defined only operator<< for LPCSTR, and then you want it to work function object on the right side.
You use word "manipulator", but you misunderstand something. Manipulator for a stream (stream from STL) is a function that performs some actions on the stream it is written to. And it works only because of this overload:
which takes a function and applies it to a stream.
Similarly you need:
Wouldn't this
do what you want?
To make it work you have to add overload of operator << for functions, than call the function from it: