Static pointer to a class method, if possible and meaningful

Usually for singleton classes, one has to write all the time something like this:

SomeSingleton::GetInstance().someVariable

And I’m looking for a simplification that can be seen everywhere, so should be put in the (header and source) files of the class itself.

So, the (non-working) stuff should look something like this:

SomeSingleton.hpp:

class SomeSingleton {
//...
    static SomeSingleton& GetInstance();
};

SomeSingleton& (*INSTANCE)();

SomeSingleton.cpp:

SomeSingleton& (* INSTANCE)() = SomeSingleton::GetInstance;

But this is misinterpreted as a redefinition, so doesn’t work. If the declaration and the definition was in the same row, that would work, but then it would not work in a header used from everywhere. Assigning the pointer to the already declared INSTANCE variable wouldn’t be simpler than simply defining the INSTANCE every file it is used in.

A workaround is to put a line

static SomeSingleton& (*INSTANCE)() = SomeSingleton::GetInstance;

into every file I use this and replace every SomeSingleton::GetInstance to INSTANCE which works but not ideal plus I’m not sure that from a design aspect it is clever to assign a singleton to a static variable (in a sense a static stuff to another static stuff).

Any ideas on this?

>Solution :

I think the only thing you are missing is extern in your header

extern SomeSingleton& (*INSTANCE)();

Leave a Reply