Listing 2: An oversimplified expression template
template<typename T, size_t n, size_t m>
class Matrix;
template<typename T, size_t n, size_t m>
class EtMatrixAdd
{
public:
EtMatrixAdd(
const Matrix<T, n, m>& lhs,
const Matrix<T, n, m>& rhs) : m_lhs(lhs), m_rhs(rhs) {}
T ElementAt(size_t n, size_t m) const
{ return m_lhs.ElementAt(n, m) + m_rhs.ElementAt(n, m); }
private:
const Matrix<T, n, m>& m_lhs;
const Matrix<T, n, m>& m_rhs;
};
// In addition to operator= of Listing 1
template<typename T, size_t n, size_t m>
Matrix<T, n, m>& operator=(
Matrix<T, n, m>& lhs,
const EtMatrixAdd<T, n, m>& rhs) {
for(int i=0; i<n; ++i)
for(int j=0; j<m; ++j)
lhs.ElementAt(i,j) = rhs.ElementAt(i,j);
return lhs;
}
// Replaces the operator+ of Listing 1
template<typename T, size_t n, size_t m>
inline EtMatrixAdd<T, n, m> operator+(
const Matrix<T, n, m>& lhs,
const Matrix<T, n, m>& rhs)
{ return EtMatrixAdd<T, n, m>(lhs, rhs); }