Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Professional C++ [eng].pdf
Скачиваний:
284
Добавлен:
16.08.2013
Размер:
11.09 Mб
Скачать

Writing Generic Code with Templates

Using Zero-Initialization of Template Types

Neither of the options presented so far for providing an initial empty value for the cells is very attractive. Instead, you may simply want to initialize each cell to a reasonable default value that you choose (instead of allowing the user to specify). Of course, the immediate question is: what’s a reasonable value for any possible type? For objects, a reasonable value is an object created with the default constructor. In fact, that’s exactly what you’re already getting when you create an array of objects. However, for simple data types like int and double, and for pointers, a reasonable initial value is 0. Therefore, what you really want to be able to do is assign 0 to nonobjects and use the default constructor on objects. You actually saw the syntax for this behavior in the section on “Method Templates with Nontype Parameters.” Here is the implementation of the Grid template constructor using the zero-initialization syntax:

template <typename T>

Grid<T>::Grid(int inWidth, int inHeight) : mWidth(inWidth), mHeight(inHeight)

{

mCells = new T* [mWidth];

for (int i = 0; i < mWidth; i++) { mCells[i] = new T[mHeight];

for (int j = 0; j < mHeight; j++) { mCells[i][j] = T();

}

}

}

Given this ability, you can revert to the original Grid class (without an EMPTY nontype parameter) and just initialize each cell element to its zero-initialized “reasonable value.”

Template Class Partial Specialization

The char* class specialization shown in the first part of this chapter is called full class template specialization because it specializes the Grid template for every template parameter. There are no template parameters left in the specialization. That’s not the only way you can specialize a class; you can also write a partial class specialization, in which you specialize some template parameters but not others. For example, recall the basic version of the Grid template with width and height nontype parameters:

template <typename T, int WIDTH, int HEIGHT> class Grid

{

public:

void setElementAt(int x, int y, const T& inElem); T& getElementAt(int x, int y);

const T& getElementAt(int x, int y) const; int getHeight() const { return HEIGHT; } int getWidth() const { return WIDTH; }

protected:

T mCells[WIDTH][HEIGHT];

};

307

Chapter 11

You could specialize this template class for char* C-style strings like this:

#include “Grid.h” // The file containing the Grid template definition shown above #include <cstdlib>

#include <cstring> using namespace std;

template <int WIDTH, int HEIGHT> class Grid<char*, WIDTH, HEIGHT>

{

public:

Grid();

Grid(const Grid<char*, WIDTH, HEIGHT>& src); ~Grid();

Grid<char*, WIDTH, HEIGHT>& Grid<char*, WIDTH, HEIGHT>::operator=( const Grid<char*, WIDTH, HEIGHT>& rhs);

void setElementAt(int x, int y, const char* inElem); char* getElementAt(int x, int y) const;

int getHeight() const { return HEIGHT; } int getWidth() const { return WIDTH; }

protected:

void copyFrom(const Grid<char*, WIDTH, HEIGHT>& src);

char* mCells[WIDTH][HEIGHT];

};

In this case, you are not specializing all the template parameters. Therefore, your template line looks like this:

template <int WIDTH, int HEIGHT> class Grid<char*, WIDTH, HEIGHT>

Note that the template has only two parameters: WIDTH and HEIGHT. However, you’re writing a Grid class for three arguments: T, WIDTH, and HEIGHT. Thus, your template parameter list contains two parameters, and the explicit Grid<char *, WIDTH, HEIGHT> contains three arguments. When you instantiate the template, you must still specify three parameters. You can’t instantiate the template with only height and width:

Grid<int, 2, 2> myIntGrid; // Uses the original Grid

Grid<char*, 2, 2> myStringGrid; // Uses the partial specialization for char *s Grid<2, 3> test; // DOES NOT COMPILE! No type specified.

Yes, the syntax is confusing. And it gets worse. In partial specializations, unlike in full specializations, you include the template line in front of every method definition:

template <int WIDTH, int HEIGHT> Grid<char*, WIDTH, HEIGHT>::Grid()

{

for (int i = 0; i < WIDTH; i++) {

for (int j = 0; j < HEIGHT; j++) {

// Initialize each element to NULL. mCells[i][j] = NULL;

}

}

}

308

Writing Generic Code with Templates

You need this template line with two parameters to show that this method is parameterized on those two parameters. Note that wherever you refer to the full class name, you must use Grid<char*, WIDTH, HEIGHT>.

The rest of the method definitions follow:

template <int WIDTH, int HEIGHT>

Grid<char*, WIDTH, HEIGHT>::Grid(const Grid<char*, WIDTH, HEIGHT>& src)

{

copyFrom(src);

}

template <int WIDTH, int HEIGHT> Grid<char*, WIDTH, HEIGHT>::~Grid()

{

for (int i = 0; i < WIDTH; i++) {

for (int j = 0; j < HEIGHT; j++) { delete [] mCells[i][j];

}

}

}

template <int WIDTH, int HEIGHT>

void Grid<char*, WIDTH, HEIGHT>::copyFrom( const Grid<char*, WIDTH, HEIGHT>& src)

{

int i, j;

for (i = 0; i < WIDTH; i++) {

for (j = 0; j < HEIGHT; j++) {

if (src.mCells[i][j] == NULL) { mCells[i][j] = NULL;

} else {

mCells[i][j] = new char[strlen(src.mCells[i][j]) + 1]; strcpy(mCells[i][j], src.mCells[i][j]);

}

}

}

}

template <int WIDTH, int HEIGHT>

Grid<char*, WIDTH, HEIGHT>& Grid<char*, WIDTH, HEIGHT>::operator=( const Grid<char*, WIDTH, HEIGHT>& rhs)

{

int i, j;

//Check for self-assignment. if (this == &rhs) {

return (*this);

}

//Free the old memory.

for (i = 0; i < WIDTH; i++) {

for (j = 0; j < HEIGHT; j++) { delete [] mCells[i][j];

}

}

309

Chapter 11

// Copy the new memory. copyFrom(rhs);

return (*this);

}

template <int WIDTH, int HEIGHT>

void Grid<char*, WIDTH, HEIGHT>::setElementAt( int x, int y, const char* inElem)

{

delete[] mCells[x][y]; if (inElem == NULL) {

mCells[x][y] = NULL; } else {

mCells[x][y] = new char[strlen(inElem) + 1]; strcpy(mCells[x][y], inElem);

}

}

template <int WIDTH, int HEIGHT>

char* Grid<char*, WIDTH, HEIGHT>::getElementAt(int x, int y) const

{

if (mCells[x][y] == NULL) { return (NULL);

}

char* ret = new char[strlen(mCells[x][y]) + 1]; strcpy(ret, mCells[x][y]);

return (ret);

}

Another Form of Partial Specialization

The previous example does not show the true power of partial specialization. You can write specialized implementations for a subset of possible types without specializing individual types. For example, you can write a specialization of the Grid class for all pointer types. This specialization might perform deep copies of objects to which pointers point instead of storing shallow copies of the pointers in the grid.

Here is the class definition, assuming that you’re specializing the initial version of the Grid with only one parameter:

#include “Grid.h”

template <typename T> class Grid<T*>

{

public:

Grid(int inWidth = kDefaultWidth, int inHeight = kDefaultHeight); Grid(const Grid<T*>& src);

~Grid();

Grid<T*>& operator=(const Grid<T*>& rhs);

void setElementAt(int x, int y, const T* inElem);

T* getElementAt(int x, int y) const;

310

Writing Generic Code with Templates

int getHeight() const { return mHeight; } int getWidth() const { return mWidth; } static const int kDefaultWidth = 10; static const int kDefaultHeight = 10;

protected:

void copyFrom(const Grid<T*>& src);

T** mCells;

int mWidth, mHeight;

};

As usual, these two lines are the crux of the matter:

template <typename T> class Grid<T*>

The syntax says that this class is a specialization of the Grid template for all pointer types. At least that’s what it’s telling the compiler. What it’s telling you and me is that the C++ standards committee should have come up with a better syntax! Unless you’ve been working with it for a long time, it’s quite jarring.

You are providing the implementation only in cases where T is a pointer type. Note that if you instantiate a grid like this: Grid<int*> myIntGrid, then T will actually be int, not int *. That’s a bit unintuitive, but unfortunately, the way it works. Here is a code example:

Grid<int*> psGrid(2, 2); // Uses the partial specialization for pointer types

int x = 3, y = 4; psGrid.setElementAt(0, 0, &x); psGrid.setElementAt(0, 1, &y); psGrid.setElementAt(1, 0, &y); psGrid.setElementAt(1, 1, &x);

Grid<int> myIntGrid; // Uses the nonspecialized grid

At this point, you’re probably wondering whether this really works. We sympathize with your skepticism. One of the authors was so surprised by this syntax when he first read about it that he didn’t believe it actually worked until he was able to try it out. If you don’t believe us, try it out yourself! Here are the method implementations. Pay close attention to the template line syntax before each method.

template <typename T>

const int Grid<T*>::kDefaultWidth;

template <typename T>

const int Grid<T*>::kDefaultHeight;

template <typename T>

Grid<T*>::Grid(int inWidth, int inHeight) : mWidth(inWidth), mHeight(inHeight)

{

mCells = new T*

[mWidth];

for (int i = 0;

i < mWidth; i++) {

mCells[i] =

new T[mHeight];

}

 

}

311

Chapter 11

template <typename T> Grid<T*>::Grid(const Grid<T*>& src)

{

copyFrom(src);

}

template <typename T> Grid<T*>::~Grid()

{

// Free the old memory.

for (int i = 0; i < mWidth; i++) { delete [] mCells[i];

}

delete [] mCells;

}

template <typename T>

void Grid<T*>::copyFrom(const Grid<T*>& src)

{

int i, j;

mWidth = src.mWidth; mHeight = src.mHeight;

mCells = new T* [mWidth];

for (i = 0; i < mWidth; i++) { mCells[i] = new T[mHeight];

}

for (i = 0; i < mWidth; i++) {

for (j = 0; j < mHeight; j++) { mCells[i][j] = src.mCells[i][j];

}

}

}

template <typename T>

Grid<T*>& Grid<T*>::operator=(const Grid<T*>& rhs)

{

//Check for self-assignment. if (this == &rhs) {

return (*this);

}

//Free the old memory.

for (int i = 0; i < mWidth; i++) { delete [] mCells[i];

}

delete [] mCells;

// Copy the new memory. copyFrom(rhs);

return (*this);

}

312