|
-
May 31st, 2010, 10:40 PM
#1
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?
-
June 1st, 2010, 12:12 AM
#2
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);
}
-
June 1st, 2010, 03:59 AM
#3
Re: overload << for singleton class
 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.
Cheers, D Drmmr
Please put [code][/code] tags around your code to preserve indentation and make it more readable.
As long as man ascribes to himself what is merely a posibility, he will not work for the attainment of it. - P. D. Ouspensky
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|