Sunday 15 September 2013

c++ - Class unable to make friends with a function that's not in its namespace -



c++ - Class unable to make friends with a function that's not in its namespace -

i'm having difficulty understanding why next mwe not compile:

#include <iostream> namespace n { class foo { friend void bar( foo& f ); void print(){ std::cout << "..." << std::endl; } // private default }; } void bar( n::foo& f ) { f.print(); } int main() { }

g++ 4.8.2 error

test.cpp: in function ‘void bar(n::foo&)’: test.cpp:8:8: error: ‘void n::foo::print()’ private void print(){ std::cout << "..." << std::endl; } // private default ^ test.cpp:14:10: error: within context

i'm missing here certainly friend function bar() can access private fellow member of class n::foo.

note that:

moving bar() namespace n resolves error. the code compiles if ::bar() not phone call n::foo::print()

why doesn't code compile is?

edit

on sec thoughts title of question not exactly describe problem. i'll edit in due course.

an unqualified friend declaration refers function in namespace containing class, introducing function namespace if hasn't been declared.

i'd move function namespace. can found argument-dependent lookup, can phone call unqualified bar(foo) without need n::.

if want in global namespace reason, you'll need declare in global namespace before can declare friend. bit messy:

// need class definition declare function namespace n {class foo;} // need function definition declare friend void bar( n::foo& ); // need class definition define function namespace n { class foo { friend void ::bar( foo& f ); void print(){ std::cout << "..." << std::endl; } // private default }; } // , function void bar( n::foo& f ) { f.print(); }

c++ namespaces argument-dependent-lookup

No comments:

Post a Comment