nen777w
nen777w

Reputation: 99

How to declare friend with static function in Outer class inside the Inner class?

Here is the simple code:

class Outer
{
public:
    class Inner
    {
        static friend void Outer::s_foo(Inner*); //<-- How to declare that?
    private:
        void inner_foo() {}
    };

    static void s_foo(Inner * inner)
    {
        inner->inner_foo();
    }
};

Is it possible to declare friendship correctly?

Upvotes: 0

Views: 55

Answers (1)

user4581301
user4581301

Reputation: 33932

This is a case where order is important. To know s_foo exists, the friend declaration must come after s_foo

class Outer
{
public:
    class Inner; // forward declaration to satisfy s_foo's argument

    static void s_foo(Inner * inner) // moved ahead of friend declaration
    {
        inner->inner_foo();
    }
    class Inner
    {
        friend void Outer::s_foo(Inner*); //No need for static here. Just need the name
    private:
        void inner_foo() {}
    };
};

As for why s_foo can see inner_foo even though it is declared later, That's just C++ being friendly. When resolving the methods C++ considers the whole class. Why it can't do the same for the friend declaration, frankly I don't know.

Upvotes: 1

Related Questions