JSTAcademy
0 XP
Dashboard
Crash Courses
Functions, Overloading & Templates
35 min
Masters+170 XP
Crash Courses · Masters

Functions, Overloading & Templates

Reusable code with function overloading and compile-time generics
35 min read+170 XP on completionCert: C++ Crash Course
Tap any word in the text below to start reading from there.

Functions, Overloading & Templates

Function Overloading

#include <iostream>
#include <string>

void print(int n) {
    std::cout << "int: " << n << std::endl;
}

void print(double d) {
    std::cout << "double: " << d << std::endl;
}

void print(const std::string& s) {
    std::cout << "string: " << s << std::endl;
}

int main() {
    print(42);          // calls print(int)
    print(3.14);        // calls print(double)
    print("hello");     // calls print(string)
    return 0;
}

Default Arguments

// Default arguments must be rightmost
void greet(const std::string& name, const std::string& greeting = "Hello") {
    std::cout << greeting << ", " << name << "!" << std::endl;
}

int main() {
    greet("Jordan");           // Hello, Jordan!
    greet("Jordan", "Hey");    // Hey, Jordan!
    return 0;
}

Function Templates

template <typename T>
T maximum(T a, T b) {
    return a > b ? a : b;
}

int main() {
    std::cout << maximum(3, 7)       << std::endl; // 7 (int)
    std::cout << maximum(3.14, 2.71) << std::endl; // 3.14 (double)
    std::cout << maximum('a', 'z')   << std::endl; // z (char)
    return 0;
}

The compiler generates a separate maximum<int>, maximum<double>, and maximum<char> — zero runtime overhead.

Multiple Template Parameters

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

std::cout << add(3, 2.5); // 5.5 (double)

constexpr Functions

constexpr int factorial(int n) {
    return n <= 1 ? 1 : n * factorial(n - 1);
}

// Evaluated at compile time when argument is a constant
constexpr int f5 = factorial(5); // 120 — computed at compile time
int arr[factorial(4)];           // 24 — array size computed at compile time

Template Specialization

// General template
template <typename T>
std::string describe(T val) {
    return "value: " + std::to_string(val);
}

// Specialization for bool
template <>
std::string describe<bool>(bool val) {
    return val ? "true" : "false";
}

std::cout << describe(42);    // value: 42
std::cout << describe(true);  // true
0%