Function Objects (Functors)

Functors vs Lambda Expressions

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

Abstract art representing computer programming

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
This Question is from the Lesson:

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.

Answers to questions are automatically generated and may not have been reviewed.

This Question is from the Lesson:

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.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 125 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved