Pages

Monday, July 28, 2025

Necessity of Templates in C++: Examples : Explain?

-> Templates enables generic programming.
-> Allow functions and classes to operate on any data type without code duplication.
-> Promotes code reusability, efficiency, and type safety.
-> Instead of writing separate functions for int, float, double, char, etc,, you can write one generic template.


#Code Example to Find Max:

#include <iostream>

using namespace std;

template<typename T>

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


#How Compiler Generates Code:

When you call max() with specific types, like:

int a = max(3, 5); // T = int
double d = max(3.5, 2.1); // T = double
char c = max('a', 'b'); // T = char

-> The compiler generates a separate versions of max for each data type during compilation(which is called template instantiation). So, it seems like as if you had written separate versions like multiple overloaded versions of the function. 

No comments:

Post a Comment

Multi-dimensional ArrayList in Java

  // import java.util.ArrayList; import java.util. * ; // import java.util.Collections; public class Classroom {     public static voi...