Templates — a C++ mechanism that allows creating generic classes and functions that work with different data types without code duplication. This is the foundation for the implementation of STL containers, algorithms, and many patterns of generic programming.
Types of templates:
Example of a class template:
template<typename T> class Box { public: Box(T value): data(value) {} T get() const { return data; } private: T data; };
Example of a function template:
template<class T> T add(const T& a, const T& b) { return a + b; }
Can you explicitly specialize only one method of a template class without specializing the entire class? If so, how is this done?
Answer:
Yes, it is possible. It is not necessary to specialize the entire class; you can simply specialize an individual method:
template <typename T> class Foo { public: void bar(); }; template <> void Foo<int>::bar() { // Specialization only of the bar method for int // Implementation }
Story
A function template was written in the project for comparison:template <typename T> bool cmp(const T& a, const T& b) { return a < b; }When used with types that do not have the
<operator, a compilation error occurred, which was hard to trace because the diagnostics were issued only when the template was instantiated, not at its definition site.
Story
A developer tried to use addition in a template function for a user-defined class, forgetting to overload the+operator. This resulted in compilation errors on the very first call with this class.
Story
When developing a container based on a class template, a method was created that did not depend on the template type but was defined outside the class without explicit specialization:template<> int MyContainer<int>::size() const { ... }This led to a linking error because the specialization was declared but not correctly implemented for all types.