functions and templates

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

One function, several types add(2, 3) and add(2.5, 0.5) both passed

Overloads

Overloads differ by parameter types Return type alone cannot distinguish them Keep overloads few, a wall of near identical names is confusing

Templates

Templates generate code at compile time Errors can be long, read the first line and then the instantiation trace Use concepts to express requirements when a template needs specific operations

Parameters

Pass small values by value Pass large objects by const & when you only read them Pass by && when you intend to move from the argument

Lambdas

int factor = 2;
auto scale = [factor](int n) { return n * factor; };

Capture by value for short lived callbacks Capture by reference only when the lifetime is obvious

Next

Classes in 05 classes

Posted