Classes with operator Functors

suggest change

Every class that overloads operator() can be used as a function object. These classes can be written by hand (often referred to as functors) or automatically generated by the compiler by writing Lambdas from C++11 on.

struct Person {
    std::string name;
    unsigned int age;
};

// Functor that finds a person by name
struct FindPersonByName {
    FindPersonByName(const std::string &name) : _name(name) {}

    // Overloaded call operator that will be called
    bool operator()(const Person &person) const {
         return person.name == _name;
    }
private:
    std::string _name;
};

std::vector<Person> v; // Assume this contains data
std::vector<Person>::iterator iFind =
    std::find_if(v.begin(), v.end(), FindPersonByName("Foobar"));
// ...

Each functor has its own type, so one function-pointer typedef cannot name every functor. Algorithms therefore accept the predicate as a template parameter, taken by value, as std::find_if does. An illustrative definition can look like:

template<typename Iterator, typename Predicate>
Iterator find_if(Iterator begin, Iterator end, Predicate predicate) {
     for (Iterator i = begin; i != end; ++i)
         if (predicate(*i))
             return i;
     return end;
}

From C++17, the predicate can be called with std::invoke: std::invoke(predicate, *i).

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents