Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Friend function of a private inner class

I have the following problem. I have a class with a private inner class. I now would like to implement a friend swap function for the inner class. However I do not know how to make a non inline swap function. If I define it in the inner class it all works fine. If someone can show me how to make it non inline I would greatly appreciate it :)

Some code do illustrate the problem:

class Outer
{
    class Inner
    {
        int data;

        friend swap(Inner& lhs, Inner& rhs)  // what is the syntax to 
        {                                    // make this function non inline?
            using std::swap;
            swap(lhs.data, rhs.data);
        }       
    }
}
like image 421
rozina Avatar asked Mar 17 '14 11:03

rozina


2 Answers

To do it you need to define it in a .cpp file just like any other function:

Outer::Inner::swap(Outer::Inner& lhs, Outer::Inner& rhs)
{
    using std::swap;
    swap(lhs.data, rhs.data);
}
like image 31
Eugene Avatar answered Oct 04 '22 18:10

Eugene


I think I found the solution. Seemed a bit strange to me at first, but it makes sense. When I tried to write the definition of the swap function in the .cpp file the compiler told me that swap does not have access to Inner since it is private. The solution was to make it this swap function a friend of Outer as well!

In code:

.h:

class Outer
{
    class Inner
    {
        int data;

        friend swap(Inner& lhs, Inner& rhs);     
    }
    friend swap(Inner& lhs, Inner& rhs);
}

.cpp:

void swap(Outer::Inner& lhs, Outer::Inner& rhs)
{
    using std::swap;
    swap(lhs.data, rhs.data);
} 
like image 62
rozina Avatar answered Oct 04 '22 17:10

rozina