© Dmitri Nesteruk 2022
D. NesterukDesign Patterns in Modern C++20https://doi.org/10.1007/978-1-4842-7295-4_22

22. Strategy

Dmitri Nesteruk1  
(1)
St. Petersburg, Russia
 
You’ll be surprised to know that you have probably used the Strategy pattern in your everyday interactions with the Standard Library. After all, any time you specify a particular sorting algorithm, for example, you are specifying a sorting strategy, that is, providing a partial definition of the overall algorithm:
vector<int> values{3,1,5,2,4};
sort(values.begin(), values.end(), less<>{});
for (int x : values)
  cout << x << ' '; // 1 2 3 4 5

In the preceding, the function less is a sorting strategy for the overall sorting algorithm. less is simply a wrapper template function for the

Get Design Patterns in Modern C++20: Reusable Approaches for Object-Oriented Software Design now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.