Reputation: 1
Currently the following code is not working:
namespace inner
{
struct Test
{
Test() : n(0) { }
friend int ::operator+(const Test& a, const Test& b);
private:
int n;
};
}
int operator+(const inner::Test& a, const inner::Test& b)
{
return a.n + b.n;
}
and the error I get is
error: 'int operator+(const inner::Test&, const inner::Test&)' should have been declared inside '::'
friend int ::operator+(const Test& a, const Test& b);
^
I thought qualifing the namespace would fix the problem but it doesn't. What's a workaround?
Upvotes: 0
Views: 110
Reputation: 254431
A friend declaration can only introduce a name into the immediately surrounding namespace.
If you want to befriend a function in any other namespace, then you'll need to declare that function, in its namespace, before the friend declaration. As the error message says.
In this case, you probably want the operator to be in inner
rather than the global namespace. Argument-dependent lookup will still find it in an expression like test_a + test_b
, even if it's not otherwise in scope.
Upvotes: 4
Reputation: 310910
You have to declare the operator before its usage in the structure.
Upvotes: 1