QT Singleton short acces question



  • Hello,

    I have a singleton.h file which I use so I can acces my text to speech object in all my classes without making everytime a new object. Now I was wondering if there is a way to short out this acces.

    First of all the two .h files:

    File:  singleton.h
    template <class T>
    class Singleton
    {
    public:
      static T* Instance()
      {
         if(!m_Instance) m_Instance =  new T;
         return m_Instance;
      }
    protected:
      Singleton();
      ~Singleton();
    private:
      Singleton(Singleton const&);
      Singleton& operator=(Singleton const&);
      static T* m_Instance;
    };
    template <class T> T* Singleton<T>::m_Instance=NULL;
    
    File: texttospeech.h
    #include <QObject>
    #include "singleton.h"
    class TextToSpeech : public QObject
    {
      Q_OBJECT
    public:
      explicit TextToSpeech(QObject *parent = 0);
      ~TextToSpeech();
    
      void init();
      void speak(const QString &text);
    };
    typedef Singleton<TextToSpeech> tts;
    

    Every time I need to acces something of the texttospeech class I must do this:
    tts::Instance()->speak("Hello Word!");

    Is there a way that I can shorten the tts::Instance() ? I though as idea that I could add #define TTS tts::Instance() after the typedef in the texttospeech.h but I would like to hear other feedbacks.

    Thanks in advanced..


  • Lifetime Qt Champion

    Hi,

    You can take inspiration from the qApp macro sources

    Hope it helps



  • HI,

    Thanks for the help!

    I know have the following define:
    #define TTS tts:Instance()

    in my texttospeech.h file and it works.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.