Sobes.tech
Junior — Middle

Can you explain what is meant by the term 'template' in programming?

sobes.tech AI

Answer from AI

In programming, the term "template" usually refers to a mechanism of generic programming that allows creating functions and classes that work with different data types without duplicating code.

In C++, templates enable defining parameterized types. For example, you can write one class or function that works with any data type specified at usage.

Example of a function template:

template <typename T>
T max(T a, T b) {
    return (a > b) ? a : b;
}

int main() {
    int x = max(3, 7);       // Used with int
    double y = max(3.5, 2.1); // Used with double
}

Templates help write more universal and reusable code, avoiding copying functions or classes for each data type.