Templates

This example illustrates how to use templates to create a function that can work with any data type.

cppCopy code#include <iostream>

template <typename T>
T max(T a, T b) {
return (a &gt; b) ? a : b;
} int main() {
std::cout &lt;&lt; max(10, 20) &lt;&lt; std::endl;       // Output: 20
std::cout &lt;&lt; max(10.5, 7.5) &lt;&lt; std::endl;   // Output: 10.5
return 0;
}

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *