I recently saw the following C++ code-snippet
template
class A : public B
{
...
};
and I am wondering in which setting such
It is used frequently in the so called "policy-based" design, i.e. you add characteristics to a base class by composition with desired derived classes, see "Modern C++ Design: Generic Programming and Design Patterns Applied" by Andrei Alexandrescu. The instantiated template class from which you derive is called the "policy". Such a design is sometimes better than inheritance, as it allows to combine policies and avoid a combinatorial explosion inevitable in the inheritance-based model.
See for example the following simple code, where RED
and BLUE
are drawing policies for a Pen
:
#include
#include
struct RED
{
std::string getColor()
{
return "RED";
}
};
struct BLUE
{
std::string getColor()
{
return "BLUE";
}
};
template
class Pencil: public PolicyClass
{
public:
void Draw()
{
std::cout << "I draw with the color " << PolicyClass::getColor() << std::endl;
}
};
int main()
{
Pencil red_pencil; // Drawing with RED
red_pencil.Draw();
Pencil blue_pencil; // Different behaviour now
blue_pencil.Draw();
return 0;
}
Can read a bit more here: http://en.wikipedia.org/wiki/Policy-based_design