ProgrammingC++ Developer

What are templates in C++? What types of templates exist? What difficulties and errors arise when designing and using templates? Show an example of a class and function template.

Pass interviews with Hintsage AI assistant

Answer.

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:

  • Function templates: allow creating a single function for different types.
  • Class templates: allow creating classes that operate with different types.
  • Templates with non-type parameters: can be parameterized not only by types but also by constant values.

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; }

Trick question.

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 }

Examples of real errors due to ignorance of the nuances of the topic.


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.