简体   繁体   中英

Declaring a function as inline friend in different namespace

I have a class declared like this :

namespace nsp1
{

 class A
 {
  public :
   inline friend void DoSomething();

  private :
   A();

   int a;
 };

}

Like this, the function DoSomething() will be in the namespace nsp1. Is there a way to declare this function to have it both inline friend and outside of the namespace?

Here is a solution:

 namespace nsp1
{
    class A;
}

inline void DoSomething(const nsp1::A & a);
 namespace nsp1
{

 class A
 {
  public :
   inline friend void ::DoSomething(const nsp1::A & a);

  private :
   A();

   int a;
 };

}

inline void DoSomething(const nsp1::A & a)
{
     std::cout<<a.a<<std::endl;//a.a is private!
}

It is not possible to do it in one go. You first need to declare the namespace and function, then define the class which befriends the function, and then define the function.

namespace nsp2
{
   void DoSomething();
}

namespace nsp1
{
   class A
   {
   public :
      friend void nsp2::DoSomething();

   private :
      A();

      int a;
   };
}

namespace nsp2
{
   inline void DoSomething()
   {
      nsp1::A a;
      a.a = 42;
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM