How to define your own output operators

A nice feature of C++ is that you can add operators to classes without modifying their declaration. So even you don’t need to modify their header file, let alone their implementation file.

Using this technique you can add output operators for your own types to ITLogMsg. The following example shows how to add an output operator for the type unsigned long to ITLogMsg

 

Operator definition (should be placed in "ITLogLibX.h", see Including the API in your modules):

 

ITLogMsg& operator << (ITLogMsg& rLogMsg, unsigned long ulValue) {

char buf[20];

 

sprintf(buf, "%lu", ulValue);

/* - max. value: 4294967295 (|ULONG_MAX|) => length 10 characters + '\0'

min. value: 0 */

 

rLogMsg << buf;

return rLogMsg;

}

 

Notes:

·      Instead of ITLogMsg& (C++ reference) you could also directly use the type ITLogMsg because it is reference counted. But using C++ references in output operator definitions and the like is the usual way and more efficient.

·      When you define output operators a non-primitive type you usually declare it as const to say that the output operation doesn’t modify it (and thus doesn’t require the parameter to be stored in a modifiable variable):

ITLogMsg& operator << (ITLogMsg& rLogMsg, const CMyType& rMyType) …

 

Example usage:

ITLogMsg LogMsg("Test", "OutputOfUnsignedLong");

LogMsg << "min. value: " << (unsigned long) 0

<< ", max. value: " << ULONG_MAX << ".";

LogMsg.Send();