1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
|
#include <cmath>
#include <iostream>
#include <string>
#include <array>
int const DATAROW_LENGTH = 4;
using namespace std;
template <size_t T_width>
class DataContainer : public array<double, T_width>
{
public:
// N.B.: no operator=, no copy constructor, no destructors are written here:
// the compiler-generated versions do the right thing.
DataContainer& Powr(double power)
{
// For each element 'elt' in this std::array
// (this object IS A std::array<>, as implied by public inheritance)
for (double& elt: *this)
elt = std::pow(elt, power);
return *this;
}
DataContainer& Squrt()
{
for (double& elt: *this)
elt = std::sqrt(elt);
return *this;
}
// Compound assignments should always return references
// Canonically, use the compound-assignment operators (for example -=, +=, <<=)
// to implement the corresponding operator (-, +, <<)
//
// N.B.: compound assignment operators return references to their left-side operand
// In these cases, *this is the left-side operand
DataContainer& operator-=(DataContainer const& rhs)
{
// Access std::array's member functions with this->memberfunction()
// You need to use 'this->' in this particular case
// Because of technical minutiae related to name lookup.
for (std::size_t i = 0; i < T_width; i++)
this->data()[i] = this->data()[i] - rhs[i];
return *this;
}
DataContainer& operator/=(double value)
{
for (double& elt: *this)
elt /= value;
return *this;
}
DataContainer& operator+=(DataContainer const& rhs)
{
for (std::size_t i = 0; i < T_width; i++)
this->data()[i] = this->data()[i] + rhs[i];
return *this;
}
void printArray() const
{
for (double const& elt: *this)
std::cout << elt << ' ';
std::cout << '\n';
}
};
// N.B.: pass lhs by value, so that a copy of it is made
// Use -= directly instead of duplicating code
//
// There is no need for these to be friend functions
// since they need no access to the private implementation of DataContainer.
template <size_t T_width>
DataContainer<T_width> operator-(DataContainer<T_width> lhs, DataContainer<T_width> const& rhs)
{
return lhs -= rhs;
}
template <size_t T_width>
DataContainer<T_width> operator+(DataContainer<T_width> lhs, DataContainer<T_width> const& rhs)
{
return lhs += rhs;
}
template <size_t T_width>
DataContainer<T_width> operator/(DataContainer<T_width> lhs, double value)
{
return lhs /= value;
}
|