Home C++ Introduction Decisions Loops Input/Output Functions Stack and Heap References Arrays Searching and Sorting Pointers Character and Strings Structures Classes Inheritance Exceptions Templatess Recursion STL Modern C++ Misc Books ----

Templates


Contents

Non-Type Template Parameter


File: non_type1.cpp
 #include <iostream>
 #include <array> // For std::array, which uses a non-type template parameter

 // A custom class template using a non-type template parameter for size
 template <typename T, int Size>
 class MyArray {
 private:
     T m_data[Size]; // The non-type parameter 'Size' determines array dimension

 public:
     // Constructor to initialize elements
     MyArray() {
         for (int i = 0; i < Size; ++i) {
             m_data[i] = T(); // Default-initialize elements
         }
     }

     // Overload the [] operator for element access
     T& operator[](int index) {
         if (index < 0 || index >= Size) {
             throw std::out_of_range("Index out of bounds");
         }
         return m_data[index];
     }

     // Const version of [] operator
     const T& operator[](int index) const {
         if (index < 0 || index >= Size) {
             throw std::out_of_range("Index out of bounds");
         }
         return m_data[index];
     }

     // Method to get the size of the array
     int getSize() const {
         return Size;
     }
 };

int main()
{
     // Instantiate MyArray with int and a size of 5
     MyArray<int, 5> intArray;

     // Assign values
     for ( int i1 = 0; i1 < intArray.getSize(); ++i1 )
     {
         intArray[i1] = i1 * 10 ;
     }

     // Print values
     std::cout << "Elements of intArray: ";
     for (int i1 = 0; i1 < intArray.getSize(); ++i1)
     {
         std::cout << intArray[i1] << " ";
     }
     std::cout << std::endl;

     // Instantiate MyArray with double and a size of 3
     MyArray<double, 3> doubleArray;
     doubleArray[0] = 1.1;
     doubleArray[1] = 2.2;
     doubleArray[2] = 3.3;

     std::cout << "Elements of doubleArray: ";
     for (int i1 = 0; i1 < doubleArray.getSize(); ++i1) {
         std::cout << doubleArray[i1] << " ";
     }
     std::cout << std::endl;

     // Example using std::array, which also employs non-type template parameters
     std::array<char, 4> charArray = {'a', 'b', 'c', 'd'};
     std::cout << "Elements of std::array: ";
     for (char c : charArray) {
         std::cout << c << " ";
     }
     std::cout << std::endl;

     return 0;
}