3.15 TEMPLATE CLASSES


3.15 TEMPLATE CLASSES

A "templatized" C++ program can work with different types of data types. For example, a templatized C++ linked-list can be used to hold elements of type int, double, char, and so on.

To explain the basic idea behind a template class, let's say that we want the following class to hold a data member whose exact type in not known in advance:

      class X{           T datum; // type T not known in advance      public:           // constructor, etc.      }; 

We, of course, have the option of defining a different class X for each different data type for the field datum, or we can be more efficient in our programming and use the following template class definition for X:

      template <class T> class X {           T datum;      public:           X( T dat ) : datum( dat ) {}           T getDatum(){ return datum; }      }; 

This parameterizes the definition of the class X by the incorporation of the parameter T in the class header. This one parameterized definition allows us to use in our program the data types X<int>, X<float>, X<double>, X<char>, X<string>, and so on, all at the same time, as illustrated by the following program:

 
//TemplateX.cc #include <string> #include <iostream> using namespace std; template <class T> class X { T datum; public: X( T dat ) : datum( dat ) {} T getDatum(){ return datum; } }; int main() { int x = 100; X<int> xobj_1( x ); double d = 1.234; X<double> xobj_2( d ); string str = "hello"; X<string> xobj_3( str ); string ret1 = xobj_3.getDatum(); cout << ret1 << endl; // output: "hello" return 0; }

Chapter 13 presents in much greater detail the notion of templatized classes and functions in C++. Chapter 13 also discusses a proposed extension to the standard Java platform that allows for the parameterization of class and method definitions.




Programming With Objects[c] A Comparative Presentation of Object-Oriented Programming With C++ and Java
Programming with Objects: A Comparative Presentation of Object Oriented Programming with C++ and Java
ISBN: 0471268526
EAN: 2147483647
Year: 2005
Pages: 273
Authors: Avinash Kak

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net