If I have a normal class I can "inject" a non-free friend function inside the class. (That among other things can be only be found by ADL).
case 1:
class A{
double p_;
friend double f(A const& a){return a.p_;}
};
If instead this is a template class I can do:
case 2:
template<class T>
class A{
double p_;
friend double f(A const& a){return a.p_;} // apparently A const& is a synomyn for A<T> const&
};
Now suppose that I need to implement f
in terms of a class that needs to be defined later. I such case I tried doing this:
case 3:
template<class T>
class A{
double p_;
friend double f(A const& a);
};
...
This already gives a warning: "warning: friend declaration ‘double f(const A&)’ declares a non-template function [-Wnon-template-friend]".
Following the advice from the compiler I can do this:
template<class T> class A;
template<class T> double f(A<T> const& a);
template<class T>
class A{
double p_;
friend double f<>(A const& a);
};
template<class T> double f(A<T> const& a){return a.p_;}
Which requires so much more code and I am not even sure it is 100% equivalent to case 2 abov which is what I want, because now I have a truly free function that happens to be a friend instead of an injected friend.
Can case 3 be modified to be 100% equivalent to case 2 and still have a definition of f
outside the class? In other words can one inject a friend function that is defined out of the class?
I tried this also, which gives a compiler error:
template<class T>
class A{
double p_;
friend double f(A<T> const& a);
};
template<class T> double A<T>::f(A<T> const& a){return a.p_;}
This answer finds the same solution but doesn't answer the question about case 3 being equivalent to case 2. What is the right way to write friend function declarations in template class?