Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading