Skip to content

Latest commit

 

History

History
30 lines (27 loc) · 1.2 KB

overload_call.md

File metadata and controls

30 lines (27 loc) · 1.2 KB

Overloading the Function Call Operator

A type with a call operator is a FunctionObject, and thus a Callable type. The call operator can have any parameters and return type, and can be defined inside or outside a class.

Sometimes you need to define it yourself, like when providing a Compare to std::set, or Hash and key eq. predicate to std::unordered_map:

Example

struct compare_abs {
    bool operator()(int x, int y) const {
        return std::abs(x) < std::abs(y);
    }
};
// ordered set containing {2, 3, -7}
std::set<int, compare_abs> s{-7, 2, 3, -2};

Alternative: Closure Type as Compare (since C++20)

std::set<int, decltype([](int x, int y) {
    return std::abs(x) < std::abs(y);
})> s;