Declare main () function as friend in C ++

I have a class that I only want clients to create one object for them for each process. Instead of singleton, the best way (I believe) is to tell clients to only create them in main (). Thus, natural coercion is to make the constructor private and main () as a friend.

It works as follows:

class A { friend int main(int, char**); A() {} }; int main(int, char **) { A a; } 

But it breaks when I need to put class A in the namespace:

 namepace ns { class A { friend int main(int, char**); A() {} }; } int main(int, char **) { ns::A a; } 

The problem is determining the scope: the compiler is now thinking

 friend int main 

means a function named main () in the ns namespace. Thus, the real main () becomes irrelevant.

So the question is: how to fix it? Of course, I need to put class A in the namespace.

+4
source share
2 answers

You need to declare main in the global namespace before the class definition, since friend declarations can only enter names in the surrounding namespace:

 int main(int, char**); 

and qualify the name when accessing it inside the namespace:

 namepace ns { class A { friend int ::main(int, char**); A() {} }; } // ^^ 
+4
source

Use " :: " to qualify something as being in the global namespace, that is:

 friend int ::main(int argc, char** argv); 
+5
source

All Articles