cpp

examples

examples.cpp⚙️
/**
 * Function Templates - Examples
 * Compile: g++ -std=c++17 -Wall examples.cpp -o examples
 */

#include <iostream>
#include <string>
#include <vector>
using namespace std;

// ============================================================
// SECTION 1: BASIC TEMPLATES
// ============================================================

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

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

template<typename T>
void swapValues(T& a, T& b) {
    T temp = a;
    a = b;
    b = temp;
}

void demoBasic() {
    cout << "--- Basic Templates ---\n" << endl;
    
    cout << "  max(3, 7) = " << maximum(3, 7) << endl;
    cout << "  max(3.14, 2.71) = " << maximum(3.14, 2.71) << endl;
    cout << "  max('a', 'z') = " << maximum('a', 'z') << endl;
    cout << "  min(\"apple\", \"banana\") = " << minimum<string>("apple", "banana") << endl;
    
    int x = 5, y = 10;
    cout << "  Before swap: x=" << x << ", y=" << y << endl;
    swapValues(x, y);
    cout << "  After swap: x=" << x << ", y=" << y << endl;
}

// ============================================================
// SECTION 2: TYPE DEDUCTION
// ============================================================

template<typename T>
void showType(T value) {
    cout << "  Value: " << value << " (type deduced)" << endl;
}

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

void demoDeduction() {
    cout << "\n--- Type Deduction ---\n" << endl;
    
    showType(42);        // T = int
    showType(3.14);      // T = double
    showType("hello");   // T = const char*
    
    cout << "  add(1, 2) = " << add(1, 2) << endl;
    cout << "  add(1.5, 2.5) = " << add(1.5, 2.5) << endl;
    
    // Explicit type specification
    cout << "  add<long>(1, 2) = " << add<long>(1, 2) << endl;
}

// ============================================================
// SECTION 3: MULTIPLE TYPE PARAMETERS
// ============================================================

template<typename T, typename U>
auto addMixed(T a, U b) {
    return a + b;  // C++14 auto return
}

template<typename T, typename U, typename R>
R convert(T value) {
    return static_cast<R>(value);
}

void demoMultipleTypes() {
    cout << "\n--- Multiple Type Parameters ---\n" << endl;
    
    auto result1 = addMixed(1, 2.5);      // int + double
    auto result2 = addMixed(1.5, 2);      // double + int
    auto result3 = addMixed(string("Hello "), "World");
    
    cout << "  1 + 2.5 = " << result1 << endl;
    cout << "  1.5 + 2 = " << result2 << endl;
    cout << "  \"Hello \" + \"World\" = " << result3 << endl;
}

// ============================================================
// SECTION 4: NON-TYPE PARAMETERS
// ============================================================

template<int N>
int multiplyBy(int x) {
    return x * N;
}

template<typename T, size_t Size>
void printArray(const T (&arr)[Size]) {
    cout << "  Array[" << Size << "]: ";
    for (size_t i = 0; i < Size; ++i) {
        cout << arr[i] << " ";
    }
    cout << endl;
}

template<typename T, T Value>
T getConstant() {
    return Value;
}

void demoNonType() {
    cout << "\n--- Non-Type Parameters ---\n" << endl;
    
    cout << "  multiplyBy<3>(5) = " << multiplyBy<3>(5) << endl;
    cout << "  multiplyBy<10>(7) = " << multiplyBy<10>(7) << endl;
    
    int nums[] = {1, 2, 3, 4, 5};
    double dbls[] = {1.1, 2.2, 3.3};
    printArray(nums);
    printArray(dbls);
    
    cout << "  getConstant<int, 42>() = " << getConstant<int, 42>() << endl;
}

// ============================================================
// SECTION 5: TEMPLATE SPECIALIZATION
// ============================================================

// Primary template
template<typename T>
string getTypeName() {
    return "unknown";
}

// Specializations
template<> string getTypeName<int>() { return "int"; }
template<> string getTypeName<double>() { return "double"; }
template<> string getTypeName<string>() { return "string"; }
template<> string getTypeName<bool>() { return "bool"; }

// Primary template
template<typename T>
void printValue(const T& value) {
    cout << "  Generic: " << value << endl;
}

// Specialization for bool
template<>
void printValue<bool>(const bool& value) {
    cout << "  Bool: " << (value ? "true" : "false") << endl;
}

// Specialization for C-string
template<>
void printValue<const char*>(const char* const& value) {
    cout << "  C-String: \"" << value << "\"" << endl;
}

void demoSpecialization() {
    cout << "\n--- Template Specialization ---\n" << endl;
    
    cout << "  Type of int: " << getTypeName<int>() << endl;
    cout << "  Type of double: " << getTypeName<double>() << endl;
    cout << "  Type of char: " << getTypeName<char>() << endl;
    
    printValue(42);
    printValue(true);
    printValue(false);
    printValue("Hello");
}

// ============================================================
// SECTION 6: GENERIC ALGORITHMS
// ============================================================

template<typename Container>
void printContainer(const Container& c) {
    cout << "  [ ";
    for (const auto& item : c) {
        cout << item << " ";
    }
    cout << "]" << endl;
}

template<typename Iterator>
void printRange(Iterator begin, Iterator end) {
    cout << "  [ ";
    while (begin != end) {
        cout << *begin++ << " ";
    }
    cout << "]" << endl;
}

template<typename Container, typename Predicate>
int countIf(const Container& c, Predicate pred) {
    int count = 0;
    for (const auto& item : c) {
        if (pred(item)) ++count;
    }
    return count;
}

void demoAlgorithms() {
    cout << "\n--- Generic Algorithms ---\n" << endl;
    
    vector<int> nums = {1, 2, 3, 4, 5};
    vector<string> words = {"apple", "banana", "cherry"};
    
    cout << "Numbers: ";
    printContainer(nums);
    
    cout << "Words: ";
    printContainer(words);
    
    cout << "Range [2,4): ";
    printRange(nums.begin() + 1, nums.begin() + 4);
    
    int evens = countIf(nums, [](int n) { return n % 2 == 0; });
    cout << "  Even count: " << evens << endl;
}

// ============================================================
// MAIN
// ============================================================

int main() {
    cout << "╔══════════════════════════════════════╗" << endl;
    cout << "║    FUNCTION TEMPLATES - EXAMPLES     ║" << endl;
    cout << "╚══════════════════════════════════════╝" << endl;
    
    demoBasic();
    demoDeduction();
    demoMultipleTypes();
    demoNonType();
    demoSpecialization();
    demoAlgorithms();
    
    cout << "\n=== Complete ===" << endl;
    return 0;
}
Examples - C++ Tutorial | DeepML