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);
}
You should declare
foo::bar::myfun
before the friend declaration and use appropriate namespace qualification (bar::
):Otherwise another function called
myfun
will be declared in thefoo
namespace by the friend declaration.