Implementing other algorithms for tuples

Expanding upon tuple_for_each(), different algorithms iterating a tuple can be implemented in a similar manner. Here is an example of how any_of() for tuples is implemented:

template <typename Tuple, typename Functor, size_t Index = 0> 
auto tuple_any_of(const Tuple& tpl, const Functor& f) -> bool { 
  constexpr auto tuple_size = std::tuple_size_v<Tuple>; 
  if constexpr(Index < tuple_size) { 
    bool success = f(std::get<Index>(tpl)); 
    return success ? 
      true: 
      tuple_any_of<Tuple, Functor, Index+1>(tpl, f); 
  } else { 
    return false; 
  } 
} 

It can then be used like this:

auto tuple = std::make_tuple(42, 43.0f, 44.0); 
auto has_44 = tuple_any_of(tuple, [](auto v){ return v == 44; }); 

The tuple_any_of tuple iterates through ...

Get C++ High Performance 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.