Professional C__ - Marc Gregoire [337]
template class Grid { // Remainder is identical to the previous version }; Code snippet from GridNonTypeDefault\Grid.h You do not need to specify the default values for WIDTH and HEIGHT in the template specification for the method definitions. For example, here is the implementation of setElementAt(): template void Grid { mCells[x][y] = inElem; } Code snippet from GridNonTypeDefault\Grid.h Now, you can instantiate a Grid with only the element type, the element type and the width, or the element type, width, and height: Grid Grid Grid Code snippet from GridNonTypeDefault\GridTest.cpp The rules for default parameters in template parameter lists are the same as for functions or methods: You can provide defaults for parameters in order starting from the right. Method Templates C++ allows you to templatize individual methods of a class. These methods can be inside a class template or in a non-templatized class. When you write a templatized class method, you are actually writing many different versions of that method for many different types. Method templates come in useful for assignment operators and copy constructors in class templates. Virtual methods and destructors cannot be method templates. Consider the original Grid template with only one parameter: the element type. You can instantiate grids of many different types, such as ints and doubles: Grid Grid Code snippet from MethodTemplates\GridTest.cpp However, Grid myDoubleGrid = myIntGrid; // DOES NOT COMPILE Grid The problem is that the Grid template copy constructor and operator= prototypes look like this: Grid(const Grid Grid The Grid copy constructor and operator= both take a reference to a const Grid Grid(const Grid Grid Note that there are no constructors or operator= that take a Grid template class Grid { public: Grid(size_t inWidth = kDefaultWidth, size_t inHeight = kDefaultHeight); Grid(const Grid template Grid(const Grid virtual ~Grid(); Grid template Grid // Omitted for brevity protected: void copyFrom(const Grid template void copyFrom(const Grid T** mCells; size_t mWidth, mHeight; }; Code snippet from MethodTemplates\Grid.h Member templates do not replace non-template members with the same name. This rule leads to problems with the