an "effect" of applying same code to different data types. it seems (at
1st) that one can go any way about it. so. there are two hammers, there
must be a reason why. what kind of nails I use each hammer for?
You are referring to polymorphism. Virtual function achieves dynamic
polymorphism at runtime while template achieves static polymorphism at
compile time.
Generally, the compiler needs to know the exact type information at
compile time in order to achieve static polymorphism. For situations
where the exact type of an object can only be known at runtime, template
is helpless.
Usually, templates and virtual functions are very different and you
should be able to use both seamlessly. A good example would be:
template <typename DimensionType>
class shape
{
public:
virtual DimensionType get_area(void)=0;
// ...
};
template <typename DimensionType>
class circle: public shape<DimensionType>
{
public:
DimensionType radius(void);
DimensionType get_area(void)
{
return 3.14*radius()*radius();
}
// ...
};
Notice the different levels of code reuse.
Ben