Hello! In our journey through functional programming in C++, we've explored currying, partial application, and functors. Today, we'll dive into an advanced example using functional objects, or functors, in combination with the powerful Boost.Range library. The goal is to deepen your understanding of how to create and utilize functional objects to make your code more modular and reusable, especially in a real-world context like adjusting employee salaries.
By the end of this lesson, you'll be able to create complex functional objects, apply them to collections using Boost.Range, and understand the benefits of such an approach.
We start by defining a struct for employees:
This structure holds basic details about an employee, which include their name and salary.
Let's create a functor that increases salary by a certain factor:
In this example:
- The constructor
SalaryIncrease(double f)
initializes the factor used to increase the salary. - The
operator()
takes anEmployee
object and returns the new salary by multiplying the current one with the factor.
Let's integrate the Employee
and SalaryIncrease
functor into a simple program. We need a collection of employees. We'll use a std::vector
:
To apply the 10% salary increase, we instantiate the SalaryIncrease
functor:
Boost.Range is a powerful library for working with ranges in a way that feels natural and expressive. We'll use it to apply our salary increase functor to each employee in our vector.
We use Boost's transformed
adaptor to apply our functor:
In this code:
boost::adaptors::transformed
applies our functor to each element in the range.- The lambda function
[&increase](const Employee& emp)
captures the functor and applies it to eachEmployee
.
To print the results, we'll use boost::for_each
:
In this code:
boost::for_each
iterates over the transformed range.- The lambda prints each employee's name and new salary.
Here is the complete program demonstrating all the concepts:
To recap, in this lesson we've:
- Defined and utilized functors in C++ to make our code more modular and reusable.
- Applied these functors to collections using Boost.Range to create elegant and readable code.
- Printed the results using
boost::for_each
.
Now it's time to get hands-on practice. You'll move to practice sessions where you'll apply these concepts using the CodeSignal IDE. This will help solidify your understanding and mastery of creating and using functional objects in C++. Happy coding!
