Sign in to follow this  
kulik

ostream and Logging, operator

Recommended Posts

Hi, I made a simple logging subsystem called LogManager, which can redirect all logged messages onto other logs or listeners, etc. Now I want to overload operator << so I can then write:
LogManager << "Something bad happened, error number: " << 1;
I tried it in numberous ways but still can't get result. This is my current code: Don't care about singleton and logMessage, these just works.
class LogManager : public Singleton<LogManager>
{
public:
	inline friend void operator <<
	( ostream& o, ostream& o2 )
	{
		stringstream s;
		s << o2;
		LogManager::getSingleton().logMessage(s.str());
	}
};
But when I include LogManager << "Hello"; anywhere, GCC says "error: expected primary-expression before '<<' token". What am I doing bad, I have zero experience with << operators, but why the hell do I need two paramaters? I guess first one is for predessor like "first << LogManager << second" but I am not sure.

Share this post


Link to post
Share on other sites
Okay the way the IOstreams do it has little to do with operator overloadding itself, the trick is called cascading functions, you could do it either by:


struct LogManager {
// ....

// doesn't have to be a friend functions.
template < typename Tp >
friend LogManager& operator<<(LogManager& l, const Tp& t) {
//....
return l;
}
};


or:


struct LogManager {
// ....
template < typename Tp >
LogManager& operator<<(const Tp& t) {
//....
return *this;
}
};


cascading functions can be done for normal (member) functions aswell.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this