Friends and templates
Both classes and functions in C++ can be templates, and we can have several different combinations - a class template can grant friendship to a non-template function if its parameter types don’t depend on the template parameters; this is not a particularly interesting case, and certainly does not solve any of the problems we’re dealing with now. When the friend function needs to operate on the template parameter types, making the right friends becomes trickier.
Friends of template classes
Let’s start by making our C
class into a template:
template <typename T> class C { T x_; public: C(T x) : x_(x) {} };
We still want to add objects of type C
and print them out. We have already considered reasons why the former is better accomplished with a non-member function, and the latter cannot be done in any other way. These reasons remain valid for class templates as well.
No problem - we can...