How do I make main a friend of my class from within a library?

后端 未结 4 819
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-12 03:03

Please see my first attempt at answering this . I neglected to tell the whole story before in an attempt to simplify things. Turns out my example works! Sorry.

The w

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-12 03:07

    @parapura provided a solution, but doesn't explain why you first have to declare main in the global scope.

    §7.3.1.2 [namespace.memdef] p3

    [...] If a friend declaration in a nonlocal class first declares a class or function the friend class or function is a member of the innermost enclosing namespace. [...]

    So with that in mind, your code would look somewhat like this:

    namespace MyNamespace
    { // MyNamespace is the innermost enclosing namespace
      // 'main' from the friend declaration is treated
      // as if it was a member of 'MyNamespace'
      int main(int argc, char** argv);
    
      class ProcessManager
      {
      public:
        friend int main(int argc, char** argv);
      private:
        void test();
      };
    };
    

    Now it should be clear why the global main function wasn't your friend.

提交回复
热议问题