Example of C++ class template Array to instantiate an Array of any element type

In this article, we will discuss how to use C++ class templates to create an array that can handle any element type. This allows for more flexible and reusable code by using templates to define generic classes.

In this tutorial you will learn:

  • How to define a class template in C++
  • How to instantiate a template class with different data types
Example of C++ class template Array
Example of C++ class template Array
Software Requirements and Linux Command Line Conventions
Category Requirements, Conventions or Software Version Used
System Linux or Windows with a C++ compiler
Software g++ compiler
Other Basic understanding of C++
Conventions # – requires given linux commands to be executed with root privileges either directly as a root user or by use of sudo command
$ – requires given linux commands to be executed as a regular non-privileged user

Defining and Using a C++ Class Template

Class templates in C++ allow you to define classes that can operate with any data type. Below is an example of defining and using a class template for an array.

DID YOU KNOW?
That C++ templates not only enhance code reusability and type safety but also enable the creation of highly optimized and efficient generic functions and classes? By leveraging templates, you can write code that works seamlessly with any data type, reducing redundancy and improving maintainability. This powerful feature is a cornerstone of C++’s ability to support both high-performance and flexible software development.

  1. Defining the Array Class Template: The following code defines a template class array that can be used to create arrays of any type.
    #ifndef ARRAY_H_
    #define ARRAY_H_
    
    #include 
    using std::cout;
    using std::endl;
    
    #include 
    using std::setw;
    
    #include 
    
    // define a clas array of type T
    // the type is not know yet and will 
    // be defined by instantiation 
    // of object of class array from main
    template< typename T > class array {
    private:
    	int size;
    	T *myarray;
    public:
    // constructor with user pre-defined size
    	array (int s) {
    	size = s;
    	myarray = new T [size];
    	}
    // calss array member function to set element of myarray 
    // with type T values
    void setArray ( int elem, T val) {
    	myarray[elem] = val;
    	}
    
    // for loop to display all elements of an array
    void getArray () {
         for ( int j = 0; j < size; j++ ) {
    // typeid will retriev a type for each value
            cout << setw( 7 ) << j << setw( 13 ) << myarray[ j ] 
    << " type: " << typeid(myarray[ j ]).name() << endl;
    	}
    	cout << "-----------------------------" << endl;
    	}
    };
    
    #endif

    Save this code into a file named array.h. This code demonstrates the declaration of a template class that can store and manipulate arrays of various data types.



  2. Instantiating and Using the Template Class: The following code shows how to instantiate and use the template class for different data types.
    #include "array.h"
    int main() 
    {
    // instantiate int_array object of class array with size 2
    array< int > int_array(2);
    // set value to a first element
    // call to array class member function to set array elements
    int_array.setArray(0,3);
    // set value to a second element
    // NOTE: any attempt to set float to an int array will be translated to int value
    int_array.setArray(1,3.4);
    
    // call to array class member function to display array elements
    int_array.getArray();
    
    // instantiate float_array object of class array with size 3
    array< float > float_array(3);
    
    // set value to a first element
    // call to array class member function to set array elements
    float_array.setArray(0,3.4);
    // set value to a second element
    float_array.setArray(1,2.8);
    
    // call to array class member function to display array elements
    float_array.getArray();
    
    // instantiate float_array object of class array with size 5
    array< char > char_array(5);
    
    // set value to a first element
    // call to array class member function to set array elements
    char_array.setArray(0,'H');
    // set value to a other array elements
    char_array.setArray(1,'E');
    char_array.setArray(2,'L');
    char_array.setArray(3,'L');
    char_array.setArray(4,'O');
    
    char_array.getArray();
    
    return 0;
    }

    Save this code into a file named main.cpp. This main function instantiates the template class for int, float, and char types, demonstrating the flexibility of class templates.

  3. Compiling and Running the Program: Compile the code with the following command:
    $ g++ main.cpp -o myarray

    Run the compiled program with the command:

    $ ./myarray

    Expected Output:

          0            3 type: i
          1            3 type: i
    -----------------------------
          0          3.4 type: f
          1          2.8 type: f
          2            0 type: f
    -----------------------------
          0            H type: c
          1            E type: c
          2            L type: c
          3            L type: c
          4            O type: c
    -----------------------------

    Compiling and Running the Program
    Compiling and Running the Program

Conclusion

This small C++ example program demonstrates the use of templates in C++. The “template class array” can instantiate arrays of any type with a single constructor and a single setArray member function.

Such behavior can also be achieved by overloading constructors and the setArray member function, but this would require separate member function declarations and definitions for each array type.

This example program instantiates three different array types: int, float, and char with a single constructor and member function using the typename T template.



Comments and Discussions
Linux Forum