Search⌘ K

Functions and Function Objects

Explore how functions and function objects work in C++. Understand their role as callables, including stateful behavior and usage in algorithms. Learn about predefined function objects for arithmetic, comparison, logical, and bitwise operations to modify container behavior effectively.

Functions

Functions are the simplest callables. They can have, apart from static variables, no state. Because the definition of a function is often widely separated from its use or even in a different translation unit, the compiler has fewer opportunities to optimize the resulting code.

C++
#include <iostream>
#include <vector>
#include <algorithm>
void square(int& i) { i = i * i; }
int main(){
std::vector<int> myVec{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
std::for_each(myVec.begin(), myVec.end(), square);
for (auto v: myVec) std::cout << v << " "; // 1 4 9 16 25 36 49 64 81 100
return 0;
}

The code above takes squares for each of the values in the given set by using std::for_each algorithm.

Function objects

At first, don’t call them functors. That’s a well-defined term from the category theory.

Function objects are objects ...