Some real-world examples
We will end this chapter by examining two examples where std::tuple
, std::tie()
, and some template metaprogramming can help us to write clean and efficient code in practice.
Example 1: projections and comparison operators
The need to implement comparison operators for classes dramatically decreased with C++20, but there are still cases where we need to provide a custom comparison function when we want to sort objects in some custom order for a specific scenario. Consider the following class:
struct Player {
std::string name_{};
int level_{};
int score_{};
// etc...
};
auto players = std::vector<Player>{};
// Add players here...
Say that we want to sort the players by their attributes: the primary sort order level_
and the secondary sort order score_
. It's not uncommon to see code like this when implementing comparison and sorting:
auto cmp = [](const Player& lhs, const Player& rhs) {
if (lhs.level_ ==...