Welcome to our deep dive into C++ Function Objects! In this lesson, we'll explore what function objects are, why they're useful, and how to create them. By the end, you'll be well-equipped to use function objects in your own C++ projects. š
In C++, a function object is an object that behaves like a function. They're also known as functors. Function objects can be assigned, passed as arguments to functions, and they can be used in various standard library algorithms.
Function objects offer several benefits:
To create a function object, you simply define a class that overloads the operator() function. Here's a simple example:
#include <iostream>
class Square {
public:
Square(int value) : num_(value) {}
int operator()(int number) {
return number * number;
}
private:
int num_;
};
int main() {
Square sq(5);
std::cout << sq(3); // Outputs: 25
return 0;
}In this example, Square is a function object that squares its input. We create a Square object, sq, with a value of 5. Then, we use the operator() function to square the number 3.
Function objects can be used with standard library algorithms. For example, consider the std::for_each algorithm, which applies a function to each element of a range. Here's how you can use our Square function object with std::for_each:
#include <vector>
#include <iostream>
#include <functional>
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5};
std::for_each(numbers.begin(), numbers.end(), Square(5));
for (const auto& number : numbers) {
std::cout << number << " "; // Outputs: 25 25 25 25 25
}
return 0;
}In this example, we use std::for_each to square each number in a vector. We pass our Square function object as the third argument, and it's applied to each number in the range.
What is a function object in C++?
Why are function objects useful?
Happy coding! š