Everyone knows the singleton pattern (very simple exemple) :
class Singleton
{
private:
static Singleton* instance;
public:
static Singleton* GetInstance() { return instance; }
void Foo() {}
};
And the use :
Singleton::GetInstance()->Foo();
I wonder, why this GetInstance()
is mandatory. I've tried to find a way to eliminate the call to this function, to be able to write for exemple... :
Singleton->Foo();
... using the class name the same way I use a variable, because of the singleton pattern, and others security like deleting the public constructor for exemple, we are sure that we only have a single instance, so why not "using the class as a variable" (quote, unquote, only syntaxic speaking of course !).
Each time, a C++ rule prohibit following exemples :
Singleton->Foo(); // (1)
Singleton()->Foo(); // (2)
Singleton.Foo(); // (3)
Singleton::Foo(); // (4)
Because :
- (1)
static Singleton* operator->() { return instance; }
is impossible, Class Member Access Operator (->) overload can't be static (see C2801), same for (2) with operator () - (3) and (4) operators . and :: can't be overloaded
Only solution here : Macros, but I'm actually using macros, and I want to find an other way and avoiding macros for this...
It's only a syntaxic interrogation, I'm not here to debate about pros and cons of singletons, but I wonder why C++ permit so many things for simplify the use syntax of users classes with overloads, user literals, and we can't eliminate this little function from the pattern.
I don't expect a solution (but if there is one, it would be great), it's just to understand why, to know if there is a explanation, a design reason, a security reason or anything else !
Thanks in advance !