overload << for singleton class
I'm trying to achieve something like the following:
Logger::Instance() << "Something sent to log file" << std::endl;
If Instance() is defined as
Code:
Logger* Logger::Instance()
{
return m_pInstance ? m_pInstance : (m_pInstance = new Logger);
}
then the following
Code:
template<typename T>
Logger& operator<<(T const& data)
{
//fout is ofstream
fout << data;
return *this;
}
results in
error C2296: '<<' : illegal, left operand has type 'Logger *'
This error make sense, but I can't think of a way around it. Can this type of effect be achieved?
Re: overload << for singleton class
One of the possible soulitions is to define your Instance() function like this
Code:
Logger& Logger::Instance()
{
return m_pInstance ? *m_pInstance : *(m_pInstance = new Logger);
}
Re: overload << for singleton class
Quote:
Originally Posted by
Coolness
Code:
Logger* Logger::Instance()
{
return m_pInstance ? m_pInstance : (m_pInstance = new Logger);
}
This function doesn't make sense. You are returning a pointer that will never be 0. That means you should have returned a reference in the first place. You should only use pointers when references don't suffice - i.e. when it makes sense for the pointer to be 0 or when you need to assign to the pointer.