Singleton template

Hi guys,

Have anyone found a way to implement a singleton template?

header:
template <class T>
struct MySingleton
{
    ~MySingleton()
    {
        clearSingletonInstance();
    }
    
    JUCE_DECLARE_SINGLETON (MySingleton <T>, false)
};

cpp:
JUCE_IMPLEMENT_SINGLETON (MySingleton <T>) // error
JUCE_IMPLEMENT_SINGLETON (MySingleton) // error
JUCE_IMPLEMENT_SINGLETON (MySingleton <String>) // error

Thanks in advance!!

Cheers
Jelle

No one who knows a solution for this…?

It was never designed for templates, so I’m not really surprised. You could dig into the macros and see if there’s a way to tweak it to make it work, but it’s not something I’d want us to spend time on, as there are now better ways to do singletons nowadays, without macros, and we should probably at some point replace the old system altogether.

@jules do you think a worthwhile addition to the Juce singletonHolder would be a

template<typename... Args>
T* createInstance(Args&&... args) 

in addition to the usual getInstance?

Right now, the JUCE_DECLARE_SINGLETON only works with classes that have a default constructor. it would be rad if it worked with classes that need arguments passed to their constructor.

Well, that’s really a different type of thing altogether - the point of the getInstance method is that it creates the object if it doesn’t already exist, but if it needs arguments then getInstance() would have to fail if called too soon. It’d be an almost entirely different class, I think.

maybe not fail, just return nullptr?

Yes, but that’s what failing means. My point is that it would be semantically different to the current singleton, so is really a different thing. And probably much easier done with just a global variable or dependency injection.