next up previous
Next: A sum Up: Elementary objects Previous: Elementary objects

A product

Toggle Background


What is a product?
A product is a collection of factors. We shall assume our product to be non-commutative. The STL vector provides such a collection (an array). Once again we use inheritance and make it a template class to be generic (it is very likely that we may have use for a product of something at later time...):

Interface: Product.H Product.H

 1 #include <vector>
 2 #include <iostream>
 3 
 4 using namespace std;
 5 
 6 /*!
 7     Implements a non-commutative product of Ts
 8 */
 9 template <class T>
10 class Product :
11     public vector<T> {
12 public:
13 
14     //! append t to product
15     Product<T> & operator *= (T const & t); 
16 };
17 
18 //! output operator for Products of Ts
19 template <class T>
20 ostream & operator << (ostream & o, Product<T> const & p);
21 
22 #include "Product.CH"
Implementation: Product.CH Product.CH
 1 template <class T>
 2 inline
 3 Product<T> & Product<T>::operator *= (T const & t)  // append t to product
 4 {
 5     push_back(t);
 6     return *this;
 7 }
 8 
 9 template <class T>
10 inline
11 ostream & operator << (ostream & o, Product<T> const & p)
12 {
13     for ( typename Product<T>::const_iterator i=p.begin() ; i!=p.end() ; ++i )
14     {
15         if ( i!=p.begin() )
16             o << "*";
17         o << *i;
18     }
19     return o;
20 }

It is a good idea to test any new object immediately to check if it behaves as expected. But how to test it if we do not have a second quantized operator at hand yet?

Our templated product is pretty general. We use strings as factors: Product_Test.C Product_Test.C

 1 #include "Product.H"
 2 #include <string>
 3 
 4 using namespace std;
 5 
 6 int main()
 7 {
 8 Product<string> p;
 9 
10     p *= string("A");
11     p *= string("B");
12     p *= string("B");
13 
14     cout << p << endl;
15 
16     return 0;
17 }
The output is (download files into a fresh directory, compile and link with g++ *.C2, run a.out)
A*B*B
Okay. That is nothing great. But be patient. It will become useful...



Footnotes

... *.C2
We assume that you have installed the GNU C++ compiler on your system.

next up previous
Next: A sum Up: Elementary objects Previous: Elementary objects
Michael Hanrath 2006-05-02