CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 12 of 12

Threaded View

  1. #1
    Join Date
    Oct 2005
    Posts
    173

    Other implementation of singleton

    For a class that has an explicit constructor with 2 parameters, I'm thinking to rewrite my Singleton. This idea is because the "getInstance()" method of Singleton. If the implementation of this method is like this:

    Code:
    static Singleton<T>::_instance = NULL;
    
    template <typename T>
    template <typename U, typename X >
    T* Singleton<T>::getInstance( U, X )
    {
       if( _instance == NULL )
          _instance = new T( U, X );
       return _instance;
    }
    Every time I call getInstance, I need to pass parameters. For the first time it's ok, but for another calls it's not fine to do this.

    Code:
    class MyClass : public Singleton<MyClass>
    {
    public:
       explicit MyClass( int, char );
       ...
    }
    But if I have a Singleton that receives the parameters and verifies inside their constructor, I think it works.

    Code:
    template< typename T >
    class Singleton
    {
    public:
    template <typename X, typename U>
    Singleton()
    {
       if( _instance == NULL )
       {
          _instance = new T( X, U );
       }
       T* getInstance()
       {
          return _instance;
       }
    }
    private:
       static T* _instance;
    };
    Ok, the problem for me is, is a good way to solve the explicit parameters in constructor with this solution? Is there a better way to do?

    Any help is very appreciated.

    Thanks
    Last edited by C#er; October 3rd, 2010 at 03:10 PM. Reason: Error in code tag

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