Templates allow you to write generic and reusable code. You can create functions or classes that work with any type. Templates enhance flexibility and reduce redundancy. Here’s an example of a simple template function:
“`cpp
#include
using namespace std;
template
T add(T a, T b) { return a + b; }
int main() {
cout << add(5, 10) << endl; // Outputs 15
return 0;
}
```
In this example, the `add` function works with any type. Templates promote code reuse and type safety.
Leave a Reply