Junior — Middle
Could you explain what is meant by a functor in programming?
sobes.tech AI
Answer from AI
In programming, especially in C++, a functor is an object that can be called as a function. Usually, it is a class or a structure with an overloaded operator(). This allows objects to be used as functions, which is convenient for passing behavior into algorithms.
Example of a functor in C++:
#include <iostream>
struct MultiplyBy {
int factor;
MultiplyBy(int f) : factor(f) {}
int operator()(int x) const {
return x * factor;
}
};
int main() {
MultiplyBy multiplyBy3(3);
std::cout << multiplyBy3(10); // Outputs 30
return 0;
}
Functors are often used in the standard library to customize algorithm behavior.