Junior — Middle
In what cases and in which parts of development is the use of templates applied?
sobes.tech AI
Answer from AI
Templates (templates) in C/C++ are used to create generic code that can work with different data types without duplication.
Templates are used in the following cases:
- When you need to write a function or class that works with different data types (e.g., sorting, containers).
- To implement generic data structures (e.g., in the standard library STL — vector, list, map).
- To increase code reuse and reduce errors related to copying and modifying code for different types.
Example of a template function:
#include <iostream>
template <typename T>
T max(T a, T b) {
return (a > b) ? a : b;
}
int main() {
std::cout << max(3, 7) << std::endl; // for int
std::cout << max(3.5, 2.1) << std::endl; // for double
return 0;
}
Templates are usually used during library development, components, when you need to ensure universality and type safety.