OverLoading operator << for ofLog


#1

Hi there, I’m wondering if it is possible to overload the ofLog "operator << " to print my custom objects. And if so, where do I need to place the overloaded functions in my code.

So far I have tried three ways, unsuccessfully.

// EngineEvent.h
class EngineEvent
{	
public:
	EngineEvent() {};
	~EngineEvent() {};

        // Attributes
        map<string, string> s_data;	
};

// EngineEvent.cpp
// First try
ofLog& operator<<(ofLog& log, const EngineEvent& obj)
{
	for (pair<string, string> keyValue : obj.s_data) {
		log << "{" << keyValue.first << ": " << keyValue.second << "}" << endl;
	}
	return log;
}

// Second try
ostream& operator<<(ostream& os, const EngineEvent& obj)
{
	for (pair<string, string> keyValue : obj.s_data) {
		os << "{" << keyValue.first << ": " << keyValue.second << "}" << endl;
	}
	return os;
}
// Desperate third try
ostringstream& operator<<(ostringstream& oss, const EngineEvent& obj)
{
	for (pair<string, string> keyValue : obj.s_data) {
		oss << "{" << keyValue.first << ": " << keyValue.second << "}" << endl;
	}
	return oss;
}

I thank you in advance !


#2

the second implementation should work but to use it from other places it needs to be declared in a .h and included from wherever you want to use it from


#3

Hello again. It seems to be okay. But just to be sure. I put the prototype into the .h file or all the function declaration ? And for all my object types, do I have to declare every classes and include them in that one file ?
For example:

// Printer.h
#include "EngineEvent.h"
#include "StrangeModel.h"

// Only prototypes and implementation elsewhere ?
ostream& operator<<(ostream& os, const EngineEvent& obj);
ostream& operator<<(ostream& os, const StrangeModel& obj);

// Or the full implemented function here 
// ...