/* The following code example is taken from the book
* "C++ Templates - The Complete Guide"
* by David Vandevoorde and Nicolai M. Josuttis, Addison-Wesley, 2002
*
* (C) Copyright David Vandevoorde and Nicolai M. Josuttis 2002.
* Permission to copy, use, modify, sell and distribute this software
* is granted provided this copyright notice appears in all copies.
* This software is provided "as is" without express or implied
* warranty, and with no claim as to its suitability for any purpose.
*/
#include
#include
template
class SArray {
public:
// create array with initial size
explicit SArray (size_t s)
: storage(new T[s]), storage_size(s) {
init();
}
// copy constructor
SArray (SArray const& orig)
: storage(new T[orig.size()]), storage_size(orig.size()) {
copy(orig);
}
// destructor: free memory
~SArray() {
delete[] storage;
}
// assignment operator
SArray& operator= (SArray const& orig) {
if (&orig!=this) {
copy(orig);
}
return *this;
}
// return size
size_t size() const {
return storage_size;
}
// index operator for constants and variables
T operator[] (size_t idx) const {
return storage[idx];
}
T& operator[] (size_t idx) {
return storage[idx];
}
protected:
// init values with default constructor
void init() {
for (size_t idx = 0; idx storage[idx] = T();
}
}
// copy values of another array
void copy (SArray const& orig) {
assert(size()==orig.size());
for (size_t idx = 0; idx storage[idx] = orig.storage[idx];
}
}
private:
T* storage; // storage of the elements
size_t storage_size; // number of elements
public:
SArray& operator+= (SArray const& b);
SArray& operator*= (SArray const& b);
SArray& operator*= (T const& s);
};
// addition of two SArrays
template
SArray operator+ (SArray const& a, SArray const& b)
{
SArray result(a.size());
for (size_t k = 0; k result[k] = a[k]+b[k];
}
return result;
}
// multiplication of two SArrays
template
SArray operator* (SArray const& a, SArray const& b)
{
SArray result(a.size());
for (size_t k = 0; k result[k] = a[k]*b[k];
}
return result;
}
// multiplication of scalar and SArray
template
SArray operator* (T const& s, SArray const& a)
{
SArray result(a.size());
for (size_t k = 0; k result[k] = s*a[k];
}
return result;
}
// multiplication of SArray and scalar
// addition of scalar and SArray
// addition of SArray and scalar
//...
// additive assignment of SArray
template
SArray& SArray::operator+= (SArray const& b)
{
for (size_t k = 0; k (*this)[k] += b[k];
}
return *this;
}
// multiplicative assignment of SArray
template
SArray& SArray::operator*= (SArray const& b)
{
for (size_t k = 0; k (*this)[k] *= b[k];
}
return *this;
}
// multiplicative assignment of scalar
template
SArray& SArray::operator*= (T const& s)
{
for (size_t k = 0; k (*this)[k] *= s;
}
return *this;
}
int main()
{
SArray x(1000), y(1000);
//...
// process x = 1.2*x + x*y
SArray tmp(x);
tmp *= y;
x *= 1.2;
x += tmp;
}