BЈовић
BЈовић

Reputation: 64253

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?

Upvotes: 1

Views: 1061

Answers (2)

UmmaGumma
UmmaGumma

Reputation: 5693

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!
}

Upvotes: 3

dalle
dalle

Reputation: 18517

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;
   }
}

Upvotes: 2

Related Questions