How to Use C++ Class Templates
Suppose you want to build a C++ class to represent complex numbers since C++ doesn't include a data type for them. The "Complex" class must handle numbers of type int, float and double. You can repeat the same code three times, or you can write it once and use templates that support generic data types. At the end, your class will look like one of the STL container classes.
Instructions
-
-
1
Become familiar with the template syntax if you aren't already. To declare a template class, insert the following line of code immediately above the class declaration, as shown:
template < class T >
class Complex{
// etc... -
2
Note that "template" and "class" are keywords. "T" is the name you give to the generic data type. T can take the form of an int, float or double. You must always enclose "class" and "T" in angle brackets. You can also use the keyword "typename" in the place of "class." Although these keywords have a somewhat different significance in C++, for the purposes of this tutorial, they're equivalent.
-
-
3
Use "T" in the class body declaration where you want generic processing. Member data "real" and "imag" are of type T because they can take the identity of any number type. The member function Real() is prototyped with T because it can return numbers of type int, float or double:
template < class T >
class Complex{
T real, imag;
public:
Complex(const T r, const T i): real( (T)0 ), ( (T)0 ){}
T Real() const;
// etc... -
4
Repeat the template definition for every member function you defined outside the class body. Also, place the T parameter inside angle brackets and insert it between the class name and the scope operator, as follows:
template < class T >
T Complex< T >::Real() const {
return real;
} -
5
Demonstrate a Complex object that uses int and one that uses float:
int main(){
Complex ni< int >(4, -5); // form 4 - j5
Complex nf< float >(4.f, -5.f); // form 4.0 - j5.0
cout << ni.Real() << endl; // print 4
cout << nf.Real() << endl; // print 4.0
} -
6
Learn how to use container classes such as vector< T > and algorithms such as copy(). Study the STL. Since the Standard Template Library is a generic library built of templates, it's an excellent place to learn how to build generic classes using templates.
-
1