cheatsheets/cpp/C++.md
2025-02-07 16:43:06 +01:00

1.2 KiB

Template

Templates are a way to dynamically "generate" functions from a template that accept user-defined arguments. They can be used instead of overloading a function. Example:

#include <iostream>
using namespace std;

// One function works for all data types. This would work
// even for user defined types if operator '>' is overloaded
//        Type (i/d)    Func  Arg  Arg
template <typename T> T myMax(T x, T y)
{
    return (x > y) ? x : y;
}

int main()
{
    // Call myMax for int
    cout << myMax<int>(3, 7) << endl;
    // call myMax for double
    cout << myMax<double>(3.0, 7.0) << endl;
    // call myMax for char
    cout << myMax<char>('g', 'e') << endl;

    return 0;
}

Source: https://www.geeksforgeeks.org/templates-cpp/

Overloading functions

Overloading a function is a way to make a function execute different instructions when different types of arguments are passed using the same function name.

#include <iostream>
using namespace std;


void add(int a, int b)
{
  cout << "sum = " << (a + b);
}

void add(double a, double b)
{
    cout << endl << "sum = " << (a + b);
}

// Driver code
int main()
{
    add(10, 2);
    add(5.3, 6.2);

    return 0;
}

Source: https://www.geeksforgeeks.org/function-overloading-c/