Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
roth_stephan_clean_c20_sustainable_software_development_patt.pdf
Скачиваний:
29
Добавлен:
27.03.2023
Размер:
7.26 Mб
Скачать

Chapter 7 Functional Programming

int main() {

const std::size_t AMOUNT_OF_NUMBERS = 100; Numbers numbers(AMOUNT_OF_NUMBERS);

std::generate(begin(numbers), end(numbers), IncreasingNumberGenerator()); std::transform(begin(numbers), end(numbers), begin(numbers), ToSquare()); std::erase_if(numbers, IsAnOddNumber<Numbers::value_type>()); std::for_each(cbegin(numbers), cend(numbers), PrintOnStdOut());

return 0;

}

The reason I show the example here again in its entirety is because we will be improving it later in this chapter.

Last but not least, let’s finalize this section about functors and look at the binary functor.

Binary Functors

As mentioned, a binary functor is a function-like object that takes two parameters. If such a functor operates on its two parameters to perform some calculation (e.g.,

addition) and returns the result of this operation, it is called a binary operator. If such a functor has a Boolean return value as a result of some test, as shown in Listing 7-16, it is called a binary predicate.

Listing 7-16.  An Example of a Binary Predicate That Compares its Two Parameters

class IsGreaterOrEqual { public:

[[nodiscard]] bool operator()(const auto& value1, const auto& value2) const noexcept {

return value1 >= value2;

}

};

311