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 > b) ? a : b;
}

int main() {
    std::cout << max(10, 20) << std::endl;       // Output: 20
    std::cout << max(10.5, 7.5) << std::endl;   // Output: 10.5
    return 0;
}

Comments

Leave a Reply

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