CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Jul 2009
    Posts
    8

    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?

  2. #2
    Join Date
    Dec 2008
    Posts
    144

    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);
    }

  3. #3
    Join Date
    Jul 2005
    Location
    Netherlands
    Posts
    2,042

    Re: overload << for singleton class

    Quote Originally Posted by Coolness View Post
    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
  •  





Click Here to Expand Forum to Full Width

Featured