When defining friend functions, you can use one of two options:
Define friend function inside class definition
namespace Test { class test { int priv; friend void foo( test const & t ) { std::cout << t.priv << std::endl; } }; }
Define them in the encompassing namespace:
namespace Test { class test { int priv; friend void foo( test const & t ); }; void foo( test const & t ) { std::cout << t.priv << std::endl; } }
But note that there are differences in the search. In particular, the first case is more restrictive (and therefore should be preferable), since it will find only ADL (Argument Dependent --aka Koening - Lookup), and in the second case, the function will be taken into account whenever this namespace is considered.
That is, for the compiler to consider the first function as an overload, the argument at the place of the call should be test , while in the second case it will be taken into account whenever the identifier matches and can be considered as a valid option if the argument is converted to test .
source share