    <rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:admin="http://webns.net/mvcb/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:content="http://purl.org/rss/1.0/modules/content/">
     <channel>
        <title>ACCU  :: C++ Templates - A Simple Example</title>
        <link>https://members.accu.org/index.php/articles/681</link>
        <description>Professionalism in Programming</description>
        <dc:language>en-us</dc:language> 
        <dc:creator>Administrator</dc:creator> 
        <admin:generatorAgent rdf:resource="http://www.xaraya.org" /> 
        <admin:errorReportsTo rdf:resource="mailto:webeditor@accu.org" />
       <sy:updatePeriod>hourly</sy:updatePeriod>
       <sy:updateFrequency>1</sy:updateFrequency>
       <docs>http://backend.userland.com/rss</docs>




<div class="xar-mod-head"><span class="xar-mod-title">Programming Topics + CVu Journal Vol 16, #4 - Aug 2004</span></div>

<table border="0" cellpadding="1" cellspacing="0">
    <tbody>
    <tr>
        <td valign="top">
            Browse in :
       </td>
       <td valign="top">

                                            <a href="https://members.accu.org/index.php/articles/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c13/">Topics</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c65/">Programming</a>
<br />

                                            <a href="https://members.accu.org/index.php/articles/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c76/">Journals</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c77/">CVu</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c101/">164</a>
<br />

                                            <a href="https://members.accu.org/index.php/articles/c65-101/">Any of these categories</a>

                    -                        <a href="https://members.accu.org/index.php/articles/c65+101/">All of these categories</a>
<br />
</td>
   </tr>
   </tbody>
</table>




<div class="xar-error">
   <p>
 <strong>Note:</strong> when you create a new publication type,
the articles module will automatically use the templates
<em>user-display-[publicationtype].xt</em>
and <em>user-summary-[publicationtype].xt</em>.
If those templates do not exist when you try to preview or display a new article,
you'll get this warning :-)  Please place your own templates in themes/<em>yourtheme</em>/modules/articles . The templates will get the extension .xt there. </p>
</div>
<div class="xar-norm xar-standard-box-padding">
   <h1><strong>Title:</strong>&nbsp;C++ Templates - A Simple Example</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 03 August 2004 13:16:06 +01:00 or Tue, 03 August 2004 13:16:06 +01:00</p>
<p><strong>Summary:</strong>&nbsp;p&gt;This article describes the C++ code for performing basic operations on matrices using templates.</p></p>
<p><strong>Body:</strong>&nbsp;<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e20" id="d0e20"></a></h2>
</div>
<p>This article describes the C++ code for performing basic
operations on matrices using templates. That means we can create a
matrix of any data type using one line and call the respective
functions.</p>
<p>The code listing <tt class="filename">opmatrix.h</tt> is the
header file in which the matrix class is described. Note that the
number of rows and columns is hard coded in the header file. So, in
the current code, a matrix of two rows and two columns has been
created. These numbers can be changed for matrices of bigger
dimensions. Also for convenience's sake, this code works only for
square matrices (matrices which have the same number of rows and
columns).</p>
<p>The header file defines the matrix as a two dimensional vector.
A vector is a container in C++ which is very similar to an array in
the C language but is more sophisticated (it manages its own memory
and you can call a number of functions to perform useful
operations.) The functions <tt class="function">readm()</tt> and
<tt class="function">printm()</tt> are used to read in the elements
of the matrix and to print the matrix.</p>
<p>Note that the <tt class="function">readm()</tt> and <tt class=
"function">printm()</tt> functions use the this pointer. The this
pointer stores the address of the current object. For example, if
we declare an object of the matrix class of type <tt class=
"type">int</tt> like this</p>
<pre class="programlisting">
matrix&lt;int&gt; a;
</pre>
<p>then the <tt class="literal">this</tt> pointer will contain the
address of the object <tt class="varname">a</tt>, i.e. <tt class=
"literal">this = &amp;a</tt></p>
<p>Therefore, saying <tt class="function">a.readme()</tt> is
equivalent to saying</p>
<pre class="programlisting">
for(int i = 0; i &lt; ROWS; ++i)
  for(int j = 0; j &lt; COLS; ++j)
    cin &gt;&gt; (&amp;a)-&gt;s[i][j];
</pre>
<p>The overloaded operators +, -, * and ~ are declared as friend
functions of the matrix, so that they can access the elements of
the matrix (which are private) in order to perform the operations.
The overloaded operator ~ is the transpose operator.</p>
<p>The + operator operates on two matrices and adds the
corresponding elements of the two matrices and prints the
result.</p>
<p>The - operator is similar to the + operates except that it
subtracts the elements of two matrices, instead of adding them.</p>
<p>The * operator needs some explanation. Matrix multiplication
works only if the number of columns of the first matrix is equal to
the number of rows of the second matrix. For example, if we have to
multiply matrices a and b, then the number of columns of matrix a
must be equal to the number of rows of matrix b. In our case this
is not a problem because we are dealing with square matrices (whose
sizes are fixed once the variables ROWS and COLUMNS are
initialized), so the number of columns of first matrix will always
be equal to the number of rows of the second matrix.</p>
<p>In order to understand how the * operator works, let us consider
a simple example:</p>
<div><img src=
"resources/Cpp%20Templates%20A%20Simple%20Example.png"></div>
<p>Now, both a and b are of dimensions 2 by 2.</p>
<p>Therefore, their product will be of dimension 2 by 2. The first
element of a*b is obtained by summing the product of the
corresponding elements of the first row of matrix a and first
column of matrix b:</p>
<p>i.e.</p>
<p>(a*b)<sub>11</sub> = 1*5 + 2*7 = 5 + 14 = 19.</p>
<p>(a*b)<sub>ij</sub> denotes the element at the intersection of
ith row and jth column of the product matrix a*b. Similarly,
(a*b)<sub>12</sub> is obtained by summing the product of the
corresponding elements of the first row of matrix a and second
column of matrix b. Similarly the other two elements can be
obtained.</p>
<p>The ~ operator transposes the elements of a matrix. By
transpose, we mean interchanging the rows and columns of a matrix.
So, a matrix (A)<sub>ij</sub> after the transpose operation becomes
(A)<sub>ji</sub></p>
<div><img src=
"resources/Cpp%20Templates%20A%20Simple%20Example%201.png"></div>
<p>.</p>
<p>The above examples may seem to be trivial, but they were
purposefully made trivial in order to understand the concepts of
basic matrix operations. If the matrices were of large dimensions,
it wouldn't be a trivial task to multiply them manually. In the
results section, operations are performed on two matrices each of
dimension 4 by 4. It is here that operator overloading proves to be
most useful. For example, if we have to find the transpose of
a+b*c, all we need to do is ~(a+b*c) and store this in a matrix and
print the resultant matrix using the <tt class=
"function">printm()</tt> function.</p>
<p>Also note that each operator accepts a constant reference to the
matrix, this is because we want each operator to perform its
function without modifying the original matrix which was given to
it.</p>
<p><span class="emphasis"><em>Rajanikanth
Jammalamadaka</em></span></p>
<pre class="programlisting">
// opmatrix.h - C++ header file

#include &lt;iostream&gt;
#include &lt;vector&gt;

using std::cin;
using std::cout;
using std::vector;
using std::endl;

const int ROWS = 2;
const int COLS = 2;

template&lt;class T&gt;
class matrix {
  // declare a vector of vectors of type T
  vector&lt; vector&lt;T&gt; &gt; s ;
public:
  // Initialize the size of s to ROWS by COLS   
  matrix() : s(ROWS, vector&lt;T&gt;(COLS)) {}
  void readm();
  void printm();
  // declare the operators +,-,*,~ as  friends
  // and with return type matrix&lt;T&gt;
  friend matrix&lt;T&gt; operator+&lt;&gt;(const matrix&amp;,
                               const matrix&amp;);
  friend matrix&lt;T&gt; operator-&lt;&gt;(const matrix&amp;,
                               const matrix&amp;);
  friend matrix&lt;T&gt; operator*&lt;&gt;(
          const matrix&lt;T&gt;&amp;, const matrix&lt;T&gt;&amp;);
  friend matrix&lt;T&gt; operator~&lt;&gt;(
                            const matrix&lt;T&gt;&amp;);
};

template&lt;class T&gt;
void matrix&lt;T&gt;::readm() {
  for(int i = 0; i &lt; ROWS; i++)
    for(int j = 0; j &lt; COLS; j++)
      cin &gt;&gt; this-&gt;s[i][j];
}

template&lt;class T&gt;
void matrix&lt;T&gt;::printm() {
  for(int i = 0; i &lt; ROWS; i++) {
    for(int j = 0; j &lt; COLS; j++)
      cout &lt;&lt; this-&gt;s[i][j] &lt;&lt; &quot;\t&quot;; 
    cout &lt;&lt; endl;
  }
}

template&lt;class T&gt;
matrix&lt;T&gt; operator+(const matrix&lt;T&gt;&amp; a,
                    const matrix&lt;T&gt;&amp; b) {
  // declare a matrix temp of type T to store
  // the result and return this matrix 
  matrix&lt;T&gt; temp;
  for(int i = 0; i &lt; ROWS; i++)
    for(int j = 0; j &lt; COLS; j++)
      temp.s[i][j] = a.s[i][j] + b.s[i][j];
  return temp;
}

template&lt;class T&gt;
matrix&lt;T&gt; operator-(const matrix&lt;T&gt;&amp; a,
                    const matrix&lt;T&gt;&amp; b) {
  matrix&lt;T&gt; temp;
  for(int i = 0; i &lt; ROWS; i++)
    for(int j = 0; j &lt; COLS; j++)
      temp.s[i][j] = a.s[i][j] - b.s[i][j];
  return temp;
}

template&lt;class T&gt;
matrix&lt;T&gt; operator*(const matrix&lt;T&gt;&amp; a,
                    const matrix&lt;T&gt;&amp; b) {
  matrix&lt;T&gt; temp;
  for(int i = 0; i &lt; ROWS; i++) {
    for(int j = 0; j &lt; COLS; j++) {
      temp.s[i][j] = 0;
      for(int k = 0; k &lt; COLS; k++)
        temp.s[i][j] += a.s[i][k] * b.s[k][j];
    }
  }
  return temp;
}
        
template&lt;class T&gt;
matrix&lt;T&gt; operator~(const matrix&lt;T&gt;&amp; trans) {
  matrix&lt;T&gt; temp;
  for(int i = 0; i &lt; ROWS; i++)
    for(int j = 0; j &lt; COLS; j++)
      temp.s[j][i] = trans.s[i][j];
  return temp;
}

// matrix.cpp - C++ Source file
#include &quot;opmatrix.hpp&quot;

int main() {
  matrix&lt;int&gt; a,b,c;  // we can also declare
   // matrices of type int, float, double etc.
  cout &lt;&lt; &quot;Enter matrix a:&quot; &lt;&lt; endl;
  a.readm();
  cout &lt;&lt; &quot;a is:&quot; &lt;&lt; endl;
  a.printm();
  cout &lt;&lt; &quot;Enter matrix b:&quot; &lt;&lt; endl;
  b.readm();

  cout &lt;&lt; &quot;b is:&quot; &lt;&lt; endl;
  b.printm();

  c = a + b;
  cout &lt;&lt; endl &lt;&lt; &quot;Result of a+b:&quot; &lt;&lt; endl;
  c.printm();
  c = a - b;
  cout &lt;&lt; endl &lt;&lt; &quot;Result of a-b:&quot; &lt;&lt; endl;
  c.printm();
  c = a * b;
  cout &lt;&lt; endl &lt;&lt; &quot;Result of a*b:&quot; &lt;&lt; endl;
  c.printm();
  cout &lt;&lt; '\n' &lt;&lt; &quot;Result of a+b*c is:&quot; &lt;&lt; '\n';
  (a+b*c).printm();
  c = ~(a+b*c);
  cout &lt;&lt; '\n' &lt;&lt; &quot;Result of transpose of &quot;
       &lt;&lt; &quot;a+b*c is:&quot; &lt;&lt; '\n';
  c.printm();
  return 0;
}
</pre>
<pre class="literallayout">
// Output

&gt; g++ matrix.cpp -o matrix
&gt; matrix

Enter matrix a:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16

a is:
1       2       3       4
5       6       7       8
9       10      11      12
13      14      15      16

Enter matrix b:
17 18 19 20
21 22 23 24
25 26 27 28
29 30 31 32

b is:
17      18      19      20
21      22      23      24
25      26      27      28
29      30      31      32

Result of a+b:
18      20      22      24
26      28      30      32
34      36      38      40
42      44      46      48

Result of a-b:
-16     -16     -16     -16
-16     -16     -16     -16
-16     -16     -16     -16
-16     -16     -16     -16

Result of a*b:
250     260     270     280
618     644     670     696
986     1028    1070    1112
1354    1412    1470    1528

Result of a+b*c is:
61189   63786   66383   68980
74025   77166   80307   83448
86861   90546   94231   97916
99697   103926  108155  112384

Result of transpose of a+b*c is:
61189   74025   86861   99697
63786   77166   90546   103926
66383   80307   94231   108155
68980   83448   97916   112384
</pre></div>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
