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

Incorporating Techniques and Frameworks

two different template classes that refer to the same variable. Because the table data is separate, double deletion would occur, as demonstrated by the following code:

char* ch = new char;

SuperSmartPointer<char> ptr1(ch);

SuperSmartPointer<int> ptr2((int*)ch); // BUG! Double deletion will occur!

One solution to this problem is to make the reference map a global variable, though globals are often frowned upon. Another solution would be to wrap the map in a nontemplate class, perhaps called MapManager, which is referenced by the SuperSmartPointer template classes.

The other issue with this implementation is that it is not thread safe. As you have read previously, threads are not a feature of the C++ language. However, threads are so common in modern programming that you should be aware of this omission. Access to the static map should be protected by a lock so that concurrent additions and deletions do not conflict with each other.

If you use the SuperSmartPointer in production code, you should consider whether the code given above is appropriate for your application or if you should add thread safety and a global map.

Double Dispatch

Double dispatch is a technique that adds an extra dimension to the concept of polymorphism. As described in Chapter 3, polymorphism lets the program determine behavior based on run-time types. For example, you could have an Animal class with a move() method. All Animals move, but they differ in terms of how they move. The move() method is defined for every subclass of Animal so that the appropriate method can be called, or dispatched, for the appropriate animal at run time without knowing the type of the animal at compile time. Chapter 10 explained how to use virtual methods to implement this run-time polymorphism.

Sometimes, however, you need a method to behave according to the run-time type of two objects, instead of just one. For example, suppose that you want to add a method to the Animal class that returns true if the animal eats another animal and false otherwise. The decision is based on two factors — the type of the animal doing the eating, and the type of the animal being eaten. Unfortunately, C++ provides no language mechanism to choose a behavior based on the run-time type of more than one object. Virtual methods alone are insufficient for modeling this scenario because they determine a method, or behavior, depending on the run-time type of only the receiving object.

Some object-oriented languages provide the ability to choose a method at run-time based on the runtime types of two or more methods. They call this feature multi-methods. In C++, however, there is no core language feature to support multi-methods. Fortunately, the double dispatch technique provides a technique to make functions virtual for more than one object.

Double dispatch is really a special case of multiple dispatch, in which a behavior is chosen depending on the run-time types of two or more objects. In practice, double dispatch, which chooses a behavior based on the run-time types of exactly two objects, is usually sufficient.

741

Chapter 25

Attempt #1: Brute Force

The most straightforward way to implement a method whose behavior depends on the run-time types of two different objects is to take the perspective of one of the objects and use a series of if/else constructs to check the type of the other. For example, you could implement a method called eats() on each Animal subclass that takes the other animal as an argument. The method would be declared pure virtual in the base class as follows:

class Animal

{

public:

virtual bool eats(const Animal& inPrey) const = 0;

};

Each subclass would implement the eats() method and return the appropriate value based on the type of the argument. The implementation of eats() for several subclasses follows. Note that the Dinosaur subclass avoids the series of if/else constructs because (according to the authors) dinosaurs eat anything.

bool Bear::eats(const Animal& inPrey) const

{

if (typeid(inPrey) == typeid(Bear&)) { return false;

}else if (typeid(inPrey) == typeid(Fish&)) { return true;

}else if (typeid(inPrey) == typeid(Dinosaur&)) { return false;

}

return false;

}

bool Fish::eats(const Animal& inPrey) const

{

if (typeid(inPrey) == typeid(Bear&)) { return false;

}else if (typeid(inPrey) == typeid(Fish&)) { return true;

}else if (typeid(inPrey) == typeid(Dinosaur&)) { return false;

}

return false;

}

bool Dinosaur::eats(const Animal& inPrey) const

{

return true;

}

The brute force approach works, and it’s probably the most straightforward technique for a small number of classes. However, there are several reasons why you might want to avoid such an approach:

742

Incorporating Techniques and Frameworks

OOP purists often frown upon explicitly querying the type of an object because it implies a design that is lacking in proper object-oriented structure.

Because all types are checked inside a single method, a subclass would have to override all cases or none. For example, if you wanted to implement a CannibalisticBear class, which ate other Bears, you would have to reimplement all the existing Bear eating behavior in the subclass.

As the number of types grows, such code can grow messy and repetitive.

This approach does not force subclasses to consider new types. For example, if you added a Donkey subclass, the Bear class would continue to compile, but would return false when told to eat a Donkey, even though everybody knows that bears eat donkeys.

Attempt #2: Single Polymorphism with Overloading

You could attempt to use polymorphism with overloading to circumvent all of the cascading if/else constructs. Instead of giving each class a single eats() method that takes an Animal reference, why not overload the method for each Animal subclass? The base class definition would look like this:

class Animal

{

public:

virtual bool eats(const Bear& inPrey) const = 0; virtual bool eats(const Fish& inPrey) const = 0; virtual bool eats(const Dinosaur& inPrey) const = 0;

};

Because the methods are pure virtual in the superclass, each subclass would be forced to implement the behavior for every other type of Animal. For example, the Bear class would contain the following methods:

class Bear : public Animal

{

public:

virtual bool eats(const Bear& inBear) const { return false; } virtual bool eats(const Fish& inFish) const { return true; }

virtual bool eats(const Dinosaur& inDinosaur) const { return false; }

};

This approach initially appears to work, but it really solves only half of the problem. In order to call the proper eats() method on an Animal, the compiler needs to know the compile-time type of the animal being eaten. A call such as the following will be successful because the compile-time types of both the eater and the eaten animals are known:

Bear myBear;

Fish myFish;

cout << myBear.eats(myFish) << endl;

743

Chapter 25

The missing piece is that the solution is only polymorphic in one direction. You could access myBear in the context of an Animal and the correct method would be called:

Bear myBear;

Fish myFish;

Animal& animalRef = myBear;

cout << animalRef.eats(myFish) << endl;

The reverse is not true. If you accessed myFish in the context of the Animal class and passed that to the eats method, you would get a compile error because there is no eats method that takes an Animal.

The compiler cannot determine, at compile time, which version to call. The following example will not compile:

Bear myBear;

Fish myFish;

Animal& animalRef = myFish;

cout << myBear.eats(animalRef) << endl; // BUG! No such method Bear::eats(Animal&)

Because the compiler needs to know which overloaded version of the eats() method is going to be called at compile time, this solution is not truly polymorphic. It would not work, for example, if you were iterating over an array of Animal references and passing each one to a call to eats().

Attempt #3: Double Dispatch

The double dispatch technique is a truly polymorphic solution to the multiple type problem. In C++, polymorphism is achieved by overriding methods in subclasses. At run time, methods are called based on the actual type of the object. The single polymorphic attempt above didn’t work because it attempted to use polymorphism to determine which overloaded version of a method to call instead of using it to determine on which class to call the method.

To begin, focus on a single subclass, perhaps the Bear class. The class needs a method with the following declaration:

virtual bool eats(const Animal& inPrey) const;

The key to double dispatch is to determine the result based on a method call on the argument. Suppose that the Animal class had a method called eatenBy(), which took an Animal reference as a parameter. This method would return true if the current Animal gets eaten by the one passed in. With such a method, the definition of eats() becomes very simple:

bool Bear::eats(const Animal& inPrey) const

{

return inPrey.eatenBy(*this);

}

At first, it looks like this solution simply adds another layer of method calls to the single polymorphic method. After all, each subclass will still have to implement a version of eatenBy() for every subclass of Animal. However, there is a key difference. Polymorphism is occurring twice! When you call the eats method on an Animal, polymorphism determines whether you are calling Bear::eats, Fish::eats, or

744

Incorporating Techniques and Frameworks

one of the others. When you call eatenBy(), polymorphism again determines which class’s version of the method to call. It calls eatenBy() on the run-time type of the inPrey object. Note that the run-time type of *this is always the same as the compile-time type so that the compiler can call the correctly overloaded version of eatenBy() for the argument (in this case Bear).

Following are the class definitions for the Animal hierarchy using double dispatch. Note that forward class declarations are necessary because the base class uses references to the subclasses.

// forward references class Fish;

class Bear; class Dinosaur;

class Animal

{

public:

virtual bool eats(const Animal& inPrey) const = 0;

virtual bool eatenBy(const Bear& inBear) const = 0; virtual bool eatenBy(const Fish& inFish) const = 0; virtual bool eatenBy(const Dinosaur& inDinosaur) const = 0;

};

class Bear : public Animal

{

public:

virtual bool eats(const Animal& inPrey) const;

virtual bool eatenBy(const Bear& inBear) const; virtual bool eatenBy(const Fish& inFish) const; virtual bool eatenBy(const Dinosaur& inDinosaur) const;

};

class Fish : public Animal

{

public:

virtual bool eats(const Animal& inPrey) const;

virtual bool eatenBy(const Bear& inBear) const; virtual bool eatenBy(const Fish& inFish) const; virtual bool eatenBy(const Dinosaur& inDinosaur) const;

};

class Dinosaur : public Animal

{

public:

virtual bool eats(const Animal& inPrey) const;

virtual bool eatenBy(const Bear& inBear) const; virtual bool eatenBy(const Fish& inFish) const; virtual bool eatenBy(const Dinosaur& inDinosaur) const;

};

745

Chapter 25

The implementations follow. Note that each Animal subclass implements the eats() method in the same way, but it cannot be factored up into the parent class. The reason is that if you attempt to do so, the compiler won’t know which overloaded version of the eatenBy() method to call because *this would be an Animal, not a particular subclass. Recall that method overload resolution is determined according the compile-time type of the object, not its run-time type.

bool Bear::eats(const Animal& inPrey) const

{

return inPrey.eatenBy(*this);

}

bool Bear::eatenBy(const Bear& inBear) const

{

return false;

}

bool Bear::eatenBy(const Fish& inFish) const

{

return false;

}

bool Bear::eatenBy(const Dinosaur& inDinosaur) const

{

return true;

}

bool Fish::eats(const Animal& inPrey) const

{

return inPrey.eatenBy(*this);

}

bool Fish::eatenBy(const Bear& inBear) const

{

return true;

}

bool Fish::eatenBy(const Fish& inFish) const

{

return true;

}

bool Fish::eatenBy(const Dinosaur& inDinosaur) const

{

return true;

}

bool Dinosaur::eats(const Animal& inPrey) const

{

return inPrey.eatenBy(*this);

}

bool Dinosaur::eatenBy(const Bear& inBear) const

746