functors in c++
Functors in C++ are objects that act like functions. They're implemented using operator overloading, specifically the operator()
function. Here are the steps to create and use a functor:
Create a Functor Class: Define a class with
operator()
overloaded. This will be the function-call operator.cpp class MyFunctor { public: void operator()(int x) { // Define functionality here // This is where the functor acts like a function std::cout << "Functor called with value: " << x << std::endl; } };
Instantiate the Functor: Create an object of the functor class.
cpp MyFunctor myFunc;
Use the Functor: Call the object like a function using
operator()
. This executes the code defined in theoperator()
function.cpp myFunc(10); // This will call the operator() function in MyFunctor
Passing Functors as Arguments: Functors can be passed as arguments to functions.
```cpp void doSomething(MyFunctor func) { func(5); }
// Usage doSomething(myFunc); // Calls the doSomething function with myFunc as argument ```
Lambda Functions as Functors: C++ also supports lambda functions which can act as functors.
```cpp auto myLambda = { std::cout << "Lambda called with value: " << x << std::endl; };
myLambda(7); // Calls the lambda function as a functor ```
Functors provide a flexible way to encapsulate functionality, especially when passing functions as arguments or when using them within algorithms that accept function objects.