Functions

Functions

Declarations, overloads, parameters, return types, and callable objects.

Functions

Declaration and definition

int add(int lhs, int rhs);

int add(int lhs, int rhs) {
    return lhs + rhs;
}

Default arguments

void log(std::string_view message, int level = 1);

Pass by value vs reference

void set_name(std::string& out, std::string_view value);
void print(const std::string& name);
void store(std::string name); // copy or move in

Return types

auto area(double w, double h) -> double {
    return w * h;
}

Overloading

void draw(int x, int y);
void draw(double x, double y);

Inline and constexpr

inline int triple(int x) { return x * 3; }
constexpr int square(int x) { return x * x; }

Lambdas as function objects

auto is_even = [](int x) { return x % 2 == 0; };

Variadic templates

template <typename... Args>
void print_all(const Args&... args);

Best-practice reminders

noexcept and contracts of intent

void swap_buffers(Buffer& lhs, Buffer& rhs) noexcept {
    lhs.swap(rhs);
}

Forwarding references

template <typename T>
void push_name(std::vector<std::string>& names, T&& name) {
    names.emplace_back(std::forward<T>(name));
}

Use forwarding references in generic wrappers that should preserve lvalue/rvalue behavior.

Callable design choices