Damien
Damien

Reputation: 300

friendship and namespace issue

I'm having troubles with friendship between a class of a namespace and a function as below:

How to tell that the friend function is outside of the namespace?

Thanks

namespace NS
{
    class Class
    {
    public:
        Class();
        virtual ~Class();

    private:
        void Foo();

        friend void Bar(Class&);
    };
}

void Bar(NS::Class& c)
{
    c.Foo();
}

Upvotes: 2

Views: 100

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409176

By using the scope operator ::

friend void ::Bar(Class&);

This tells the compiler that Bar is in the global scope.


Apparently the Bar function needs to be declared before it's used in the friend declaration when using the scope operator. The problem is that for Bar to be declared you need to declare both the namespace NS and the class NS::Class.

Something like this

namespace NS
{
    class Class;
}

extern "C"
{
    void Bar(NS::Class& c);
}

namespace NS
{
    class Class
    {
    public:
        Class();
        virtual ~Class();

    private:
        void Foo() {}

        friend void ::Bar(Class&);
    };
}

void Bar(NS::Class& c)
{
    c.Foo();
}

Upvotes: 5

Related Questions