Professional C__ - Marc Gregoire [334]
The type specification is important; neither of the following two lines compiles:
Grid test; // WILL NOT COMPILE
Grid<> test; // WILL NOT COMPILE
The first causes your compiler to complain with something like, “use of class template requires template argument list.” The second causes it to say something like, “wrong number of template arguments.”
If you want to declare a function or method that takes a Grid object, you must specify the type stored in that grid as part of the Grid type:
void processIntGrid(Grid { // Body omitted for brevity } Code snippet from Grid\GridTest.cpp Instead of writing the full Grid type everytime, for example Grid typedef Grid Now you can write code as follows: void processIntGrid(IntGrid& inGrid) { } The Grid template can store more than just ints. For example, you can instantiate a Grid that stores SpreadsheetCells: Grid SpreadsheetCell myCell; mySpreadsheet.setElementAt(3, 4, myCell); Code snippet from Grid\GridTest.cpp You can store pointer types as well: Grid myStringGrid.setElementAt(2, 2, "hello"); Code snippet from Grid\GridTest.cpp The type specified can even be another template type. The following example uses the vector template from the standard template library (introduced in Chapter 1): Grid vector gridOfVectors.setElementAt(5, 6, myVector); Code snippet from Grid\GridTest.cpp You can also dynamically allocate Grid template instantiations on the heap: Grid myGridp->setElementAt(0, 0, 10); int x = myGridp->getElementAt(0, 0); delete myGridp; Code snippet from Grid\GridTest.cpp How the Compiler Processes Templates In order to understand the intricacies of templates, you need to learn how the compiler processes template code. When the compiler encounters template method definitions, it performs syntax checking, but doesn’t actually compile the templates. It can’t compile template definitions because it doesn’t know for which types they will be used. It’s impossible for a compiler to generate code for something like x = y without knowing the types of x and y. When the compiler encounters an instantiation of the template, such as Grid This instantiation process explains why you need to use the Grid Selective Instantiation The compiler generates code only for the class methods that you actually call for a particular type. For example, given the preceding Grid template class, suppose that you write this code (and only this code) in main(): Grid myIntGrid.setElementAt(0, 0, 10); The compiler generates only the 0-argument constructor, the destructor, and the setElementAt() method for an int version of the Grid. It does not generate other methods like the copy constructor, the assignment operator, or getHeight(). Template Requirements on Types When you write code that