One of its notable uses is to achieve static polymorphism, which is a compile time polymorphism and thus does not have to pay the overhead associated with virtual functions (namely, the overhead of a virtual function call and the generation of typeids). Consider the following example, adapted from Wikipedia's example on C++ (dynamic) polymorphism [1]:
template< Derived >Note that Animal< Cat > and Animal< Dog > are two unrelated classes, this means there is no common base class between a Cat and a Dog. Dynamic polymorphism can be reintroduced by making Animal inherit from an AnyAnimal class which defines `virtual string talk() = 0;`, or non-intrusively by means of type erasure.
class Animal
{
string talk(){ return static_cast< Derived* >( this )->talk(); }
};
class Cat : public Animal< Cat >
{
string talk() { return "Meow!"; }
};
class Dog : public Animal< Dog >
{
string talk() { return "Arf! Arf!"; }
};
[1] Wikipedia - Polymorphism in object-oriented programming
No comments:
Post a Comment