Search code examples
c++classtemplatesfriend

Friend functions and namespaces. Cannot access private member in class


So I have a class inside a foo namespace, which includes a friend function. Now I want the definition of the friend function to be in a different namespace bar so it can be called the way you see below. The error I get is that the private member val cannot be accessed.

Question: Why?

#include <iostream>

namespace foo 
{
    template<typename T>
    class myclass
    {
    private:
        T val;
    public:
        myclass(T v) : val(v) {}

        template<class U>
        friend void myfun(myclass<U>);
    };

    namespace bar 
    {
        template<class U>
        void myfun(myclass<U> a)
        {
            std::cout << a.val;
        }
    } //bar
} //foo

int main()
{
    foo::myclass<int> a(5);
    foo::bar::myfun(a);
}

Solution

  • You should declare foo::bar::myfun before the friend declaration and use appropriate namespace qualification (bar::):

    namespace foo 
    {
        template<typename T>
        class myclass;
    
        namespace bar 
        {
            template<class U>
            void myfun(myclass<U> a);
        } //bar
    
        template<typename T>
        class myclass
        {
        private:
            T val;
        public:
            myclass(T v) : val(v) {}
    
            template<class U>
            friend void bar::myfun(myclass<U>);
        };
    
    } //foo
    

    Otherwise another function called myfun will be declared in the foo namespace by the friend declaration.