Department of Engineering

IT Services

C++ Templates and Friends

This document assumes you're familiar with the idea of friends and of templates.

Look at this program. It's a completion of example code from Bjarne Stroustrup's "The C++ Programming Language" (Special Edition, section C.13.2, p.854)

template<class T> class Matrix;
template<class T> class Vector;

template<class T> Vector<T> operator*(const Matrix<T>& m, const Vector<T>& v)
  Vector<T> r;
  for (int i=0;i<4;i++) {
    for(int j=0;j<4;j++)
  return r;

template<class T> class Vector{
  T v[4];
  friend Vector operator*<> (const Matrix<T>&, const Vector&);

template<class T> class Matrix{
  Vector<T> v[4];
  friend Vector<T> operator*<> (const Matrix&, const Vector<T>&);

int main() {
  Matrix<int> m1;
  Vector<int> v1,v2;

My attention was drawn to the example because it uses <>, which I hadn't seen before. To understand the code I suggest you start at the Vector definition. Vector objects have 4 elements. Matrix objects have 4 Vectors. Both have the operator* function as a friend so that the function can access their private fields. The <> on the friend lines is so that the compiler doesn't make the default assumption that operator* is a non-template function.

Now look at the top of the file. The first 2 lines are forward declarations - necessary because of the interlinked nature of the subsequent code's use of the defined classes. The operator* function itself is straightforward if you've met const, references and templates before.

But I don't know why the signatures of operator* in the 2 class definitions are different. Experimenting, I found that they can be the same (both argument definitions ending in <T>&) so somehow the "missing" details are being picked up by default in the original code.

See Also