Association (i.e. a solution without templates) is preferable, as it offers you more flexibility, allows you to change the implementation of the distance at run time, generates error messages and cleaner object files (fewer characters).
In addition, classes created from a template parameterized by different types (distance implementation) will be considered different types and will not be interchangeable: MyClass<EuclideanDistance> is a different type than MyClass<MinkowskiDistance> . This will force you to do all the functions that work with MyClass templates, and also ultimately lead to more complexity without any additional benefits.
Templates should be used when you need to weaken the type safety of a language, for example, when you write a class that should work with several types of unrelated (not derived from a common base class / interface), which nevertheless behave in a similar way (for example, all have a member function kwak() ). This is called duck-typing : types are not formally related to each other, but they all have similar properties.
In case you cannot guarantee that all distance implementations will be obtained from a common base class / interface, you may need to use templates. Otherwise, a simple and flexible association is preferred.
Adam zalcman
source share