
"Neal Becker" <ndbecker2@gmail.com> wrote in message news:djogoc$u8q$1@sea.gmane.org...
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... };
The one thing I'd be concerned about is slicing. struct Base {}; struct Derived : public Base {int x; }; // Note that Derived does have data members.; Derived d; Single<Base> foo(d); Under these circumstances, does calling foo.end(), which will return an address in the middle of d, cause any problems? Joe Gottman