// template9.cpp By: Aiman Hanna - ©1993-2005 Aiman Hanna // This program illustrates Nontype template arguments. So far, we have used // types as template arguments using the class or typename keyword. Although typenames // are most common when using templates, there are other possibilities. Integer constants // are a common example. // In addition, the program illustrates that by using template arguments for the bounds, // they become part of the type. This means that compatibility between variables of different // sizes will be checked at compile time as part for the process of type checking, rather than // needing to be checked at run time. // Key Points: 1) Nontype template arguments #include template class Matrix { public: Matrix(); void showInfo(); void initMatrix(); private: T dataArr[ROWS][COLUMNS]; }; template Matrix< T, ROWS, COLUMNS>::Matrix() { cout << "Creating a matrix with " << ROWS << " rows, and " << COLUMNS << " columns." << endl; } template void Matrix::initMatrix() { int i, j; for (i = 0; i<= (ROWS - 1); i++) { for (j = 0; j <= (COLUMNS -1); j++) { dataArr[i][j] = i * j * 5; } } } template void Matrix::showInfo() { int i, j; for (i = 0; i <= (ROWS - 1); i++) { for (j = 0; j <= (COLUMNS -1); j++) { cout << dataArr[i][j] << '\t'; } cout << endl; } } int main( ) { Matrix m1; m1.initMatrix(); m1.showInfo(); cout << endl << endl; Matrix m2; m2.initMatrix(); m2.showInfo(); cout << endl << endl; Matrix m3; m3.initMatrix(); m3.showInfo(); cout << endl << endl; Matrix m4; m4.initMatrix(); m4.showInfo(); // The following would be illegal // m1 = m2; // m1 = m3; // However, this is okay. Because the row and columns sizes are known at compile // time, the space for the elements can be allocated in an array, and does not // need to be dynamically managed. m1 = m4; cout << endl << endl; m1.showInfo(); return 0; } // The output of the program /* Creating a matrix with 3 rows, and 4 columns. 0 0 0 0 0 5 10 15 0 10 20 30 Creating a matrix with 4 rows, and 7 columns. 0 0 0 0 0 0 0 0 5 10 15 20 25 30 0 10 20 30 40 50 60 0 15 30 45 60 75 90 Creating a matrix with 4 rows, and 7 columns. 0 0 0 0 0 0 0 0 5 10 15 20 25 30 0 10 20 30 40 50 60 0 15 30 45 60 75 90 Creating a matrix with 3 rows, and 4 columns. 0 0 0 0 0 5 10 15 0 10 20 30 0 0 0 0 0 5 10 15 0 10 20 30 */