When to Use a Functor Instead of a Function in C++?
Last Updated :
11 Mar, 2024
In C++, both functors and functions can be used to encapsulate behavior and provide callable objects. Still, there are specific scenarios where using a functor is more advantageous than a regular function. In this article, we will learn when to use a functor instead of a function in C++.
When to Prefer Functors Instead of Function?
In C++, prefer to use a functor instead of a function in the following cases:
1. Stateful Computations
If we need to maintain state information between calls, functors are a good choice. Unlike regular functions, functors can store state information in member variables and use it across multiple calls.
Example:
C++
#include <iostream>
using namespace std;
struct Counter {
int count = 0;
void operator()()
{
cout << "Count: " << count++ << endl;
}
};
int main()
{
Counter counter;
counter();
counter();
return 0;
}
|
2. Parameterized Behavior
Functors can be parameterized when they are constructed. This allows you to create a functor with specific behavior that can be used later.
Example:
C++
#include <iostream>
using namespace std;
struct Multiplier {
int factor;
Multiplier( int factor)
: factor(factor)
{
}
int operator()( int input) { return input * factor; }
};
int main()
{
Multiplier multiplyByThree(
3);
cout << "3 * 5 = " << multiplyByThree(5) << endl;
return 0;
}
|
3. Overloading Function Call Operator
Functors allow overloading of the function call operator that means we can have different versions of the operator() function that take different numbers or types of parameters, providing more flexibility.
Example:
C++
#include <iostream>
#include <string>
using namespace std;
struct OverloadedFunctor {
void operator()( int x)
{
cout << "Integer: " << x << endl;
}
void operator()( const string& x)
{
cout << "String: " << x << endl;
}
};
int main()
{
OverloadedFunctor functor;
functor(42);
functor( "Hello, Functor!" );
return 0;
}
|
Output
Integer: 42
String: Hello, Functor!
4. Use with STL Algorithms
Many STL algorithms like std::sort
, std::transform
, etc., accept functors as arguments so, functors can be used to customize the behavior of these algorithms.
Example:
C++
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
struct Multiply {
int operator()( int x) const { return x * 2; }
};
int main()
{
vector< int > vec = { 1, 2, 3, 4, 5 };
vector< int > result(vec.size());
transform(vec.begin(), vec.end(), result.begin(),
Multiply());
for ( int i : result) {
cout << i << " " ;
}
cout << endl;
return 0;
}
|
Share your thoughts in the comments
Please Login to comment...