Say I have a class that can use different types of distance functions (Euclidean distance, etc) to do some comparisons. I have implemented these functions as subclasses of a class Distance:
class Distance;
class EuclideanDistance : public Distance;
class OtherDistance : public Distance;
It seems that to choose which type of distance to use, I could do:
template <typename TDistance>
class MyClass;
and instantiate it with:
MyClass<EuclideanDistance> instance;
or accomplish the same thing with:
class MyClass
{
public:
Distance* myDistanceFunction;
}
and instantiating it with
MyClass instance;
instance.myDistanceFunction = new EuclideanDistance;
are there any advantages of one method over the other?
Thanks,
David
Association (i.e. the solution without templates) is preferable since it offers you more flexibility, allows you to change distance implementation at runtime, generates cleaner error messages and cleaner object files (fewer symbols).
Also, classes generated from the template parametrized with different types (distance implementations) will be considered different types and will not be interchangeable:
MyClass<EuclideanDistance>is a different type thanMyClass<MinkowskiDistance>. This will force you to make all functions that operate onMyClasstemplates as well and will ultimately lead to greater complexity with no added benefits.Templates should be used when you need to relax type-safety of the language, for example when you are writing a class which should operate on a number of unrelated types (not derived from a common base class/interface) which nonetheless behave in a similar manner (e.g. all have a
kwak()member function). This is called duck-typing: types are formally unrelated but all exhibit similar properties.In case you’re prevented from ensuring that all distance implementations derive from a common base class/interface, you may need to use templates. Otherwise, prefer simple and flexible association.