Boost logo

Boost :

From: Neal Becker (ndbecker2_at_[hidden])
Date: 2005-10-26 13:09:13


Suppose one adopts the range concept. All algorithms are written to accept
ranges as arguments.

It is common to want to implement a function F, which operates on one data
element. For example:

template<typename T>
T sqr (T x) { return x * x; }

Also, implement a version that operates on a container. This could be done
by defining only the single element version, and a version of transform,
that operates on ranges.

Here's an interesting idea. Suppose instead that only the range version of
F is defined, but a range type is made that encapsulates a single element.
Again, only 1 version of F needs to be defined.

Here is an outline:
template<typename T>
struct Single {
  typedef T* iterator;
  typedef const T* const_iterator;
  typedef size_t size_type;
  Single (T& _x) : x (_x) {}
  T& x;
  size_t size() const { return 1; }
  iterator begin() { return &x; }
  const_iterator begin() const { return &x; }
  iterator end() { return &x+1; }
  const_iterator end() const { return &x+1; }
// not complete yet...
};

// Test program...
template<typename out_t, typename in_t>
out_t copy (in_t const& in) {
  out_t out (boost::size (in));
  std::copy (boost::begin (in), boost::end (in), boost::begin (out));
  return out;
}

int main() {
  using namespace std;
  using namespace boost;

  int x;
  Single<int> s (x);
  vector<int> v = copy<vector<int> > (s);
}
            


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