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 declare template functions to go with our template classes and do the work that the non-template functions used to do in the previous section. Let's start with operator+():

template <typename T> C<T> operator+(const C<T>& lhs, const C<T>& rhs) {     return C<T>(lhs.x_ + rhs.x_); }

This is the same function that we saw previously, ...

Get Hands-On Design Patterns with C++ now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.