Labs ICT
Pro Login

Function Templates

C++ Function Templates

A function template acts as a blueprint for creating functions with different data types. The type parameter typename T is replaced at compile time with the actual type used. Function templates support multiple type parameters, and the compiler deduces types from the arguments you pass, making generic functions extremely concise.

#include <iostream>

template <typename T>
T add(T a, T b) {
    return a + b;
}

int main() {
    std::cout << add(5, 3) << "\n";
    std::cout << add(2.5, 1.5) << "\n";
    std::cout << add(std::string("Hello "), std::string("World"));
    return 0;
}
Try it Yourself →