Boost logo

Boost :

From: jsiek_at_[hidden]
Date: 2000-08-17 12:41:06


Here's a concrete example of why free functions are so great.

==============================================================================

joe/Vector.h:
  namespace joe {
    struct Vector {
      double operator[](int i);
      int Size();
    };
  }

suzy/VectorOps.h (version 1, using members):
  namespace suzy {
    template <class Vector>
    vector_add(Vector& x, Vector& y, Vector& z) {
      for (int i = 0; i < z.size(); ++i)
        z[i] = x[i] + y[i];
    }
  }

jeremy/solver.h
  namespace jeremy {
    solver(...) {
      ...
      joe::Vector x, y, z;

      suzy::vector_add(x, y, z); // doh! won't compile because Size()
                                 // is capitalized in joe's Vector
      ...
    }
  }

==============================================================================

suzy/VectorOps.h (version 2, using free functions):
  namespace suzy {
    template <class Vector>
    vector_add(Vector& x, Vector& y, Vector& z) {
      for (int i = 0; i < size(s); ++i)
        z[i] = x[i] + y[i];
    }
  }

jeremy/solver.h:

  // do the external adaptation trick: specialize the free function
  int size(const joe::Vector& x) { return x.Size(); }

  namespace jeremy {
    solver(...) {
      ...
      joe::Vector x, y, z;

      suzy::vector_add(x, y, z); // problem solved!
      ...
    }
  }

Ciao,

Jeremy


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk