Welcome back, coding enthusiast! Today, we're diving into the exciting world of C++ Functors, also known as Function Objects. By the end of this lesson, you'll understand what Functors are, why they're important, and how to use them in your projects. Let's get started!
Functors are objects that can be used in place of functions. They encapsulate both data and functions, allowing them to be treated as first-class citizens in C++. This means they can be passed as arguments to other functions, returned from functions, and stored in containers just like any other object.
Functors provide several benefits over traditional functions:
Let's create a simple Functor to demonstrate its power. We'll create a Square Functor that takes a number and returns its square.
#include <iostream>
class Square {
public:
int operator()(int number) {
return number * number;
}
};
int main() {
Square sq;
std::cout << sq(5) << std::endl; // Output: 25
return 0;
}In this example, we've created a Square class that overloads the parentheses () operator to return the square of a number. In the main() function, we create an instance of Square and call it as if it were a function.
C++ Standard Library provides several Functor classes that you'll find useful in your projects. Let's look at two examples: std::plus and std::negate.
The std::plus Functor adds two numbers. Here's an example:
#include <iostream>
#include <functional>
int main() {
std::function<int(int, int)> add = std::plus<>;
std::cout << add(3, 4) << std::endl; // Output: 7
return 0;
}In this example, we've used std::plus<> to create a function that adds two integers.
The std::negate Functor negates a number. Here's an example:
#include <iostream>
#include <functional>
int main() {
std::function<int(int)> negate = std::negate<>;
std::cout << negate(5) << std::endl; // Output: -5
return 0;
}In this example, we've used std::negate<> to create a function that negates an integer.
What does `std::plus<>()` do in C++?
In this lesson, you learned about Functors and how they can be used to encapsulate both data and functions, making them first-class citizens in C++. You also saw examples of creating a simple Functor and using std::plus and std::negate from the Standard Library. Keep practicing, and you'll soon be able to create powerful reusable code using Functors!
Stay tuned for more lessons on C++, and remember to CodeYourCraft with confidence! šÆ