Functors vs Lambda Expressions

When should I use a functor instead of a lambda expression in C++?

Both functors and lambda expressions allow you to define callable objects in C++. However, there are situations where one may be preferred over the other:

Use a functor when:

  • You need to maintain state across multiple calls
  • You require the callable to have a specific type (e.g., for template specialization)
  • You need to define multiple overloads of the operator()
  • You want to take advantage of class features like inheritance or member functions

Use a lambda expression when:

  • You need a simple, one-off callable without extra overhead
  • You don't need to maintain state across calls
  • You want to capture variables from the surrounding scope

For example, a functor is a good choice for a custom comparator in a sorting algorithm, as it can maintain state and provide a specific type:

#include <algorithm>
#include <iostream>
#include <vector>

class CustomCompare {
 public:
  CustomCompare(int t) : threshold(t) {}

  bool operator()(int a, int b) const {
    return (a > threshold) && (a < b);  
  }

 private:
  int threshold;
};

int main() {
  std::vector<int> vec{1, 5, 2, 4, 3};

  std::sort(
    vec.begin(), vec.end(), CustomCompare(3));  

  for (int i : vec) {
    std::cout << i << " ";
  }
  std::cout << "\n";
}
1 5 2 4 3

On the other hand, a lambda is better suited for a simple, one-time operation:

#include <iostream>
#include <algorithm>
#include <vector>

int main() {
  std::vector<int> vec {1, 2, 3, 4, 5};

  auto it = std::find_if(vec.begin(), vec.end(),
    [](int i){ return i > 3; });

  std::cout << *it << "\n";
}
4

Function Objects (Functors)

This lesson introduces function objects, or functors. This concept allows us to create objects that can be used as functions, including state management and parameter handling.

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Non-Operator Overloads in Functors
Can a functor class contain non-operator overloads, and how do I call them?
Templated operator() in Functors
Can the operator() in a functor be a template function?
Functors and Inheritance
Can a derived class override the operator() of a base functor class?
Functor vs Function Performance
Is there a performance difference between using functors and regular functions?
Capturing this in Functors
Can a functor capture the this pointer, and what are the implications?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant