I have made the following tuple:
I want to know how should I iterate over it? There is tupl_size()
, but reading the documentation, I didn't get how to utilize it. Also I have search SO, but questions seem to be around Boost::tuple
.
auto some = make_tuple("I am good", 255, 2.1);
So, we have two methods here, to iterate through the values of a tuple: Using Variadic Templates and metaprogramming (No use of std::apply). Using Variadic Templates and std::apply.
The basic idea is to turn tuples into a range with begin() and end() methods to provide iterators. The iterator itself returns a std::variant<...> which can then be visited using std::visit . Read-only access is also supported by passing a const std::tuple<>& to to_range() .
The new std::array and std::tuple containers provide developers with additional ways to manage structured data efficiently.
Using std::queue In other words, std::queue is not meant to be iterated over. If you need to iterate over a std::queue , you can create a copy of it and remove items from the copy, one at a time, using the standard pop function after processing it.
template<class F, class...Ts, std::size_t...Is> void for_each_in_tuple(const std::tuple<Ts...> & tuple, F func, std::index_sequence<Is...>){ using expander = int[]; (void)expander { 0, ((void)func(std::get<Is>(tuple)), 0)... }; } template<class F, class...Ts> void for_each_in_tuple(const std::tuple<Ts...> & tuple, F func){ for_each_in_tuple(tuple, func, std::make_index_sequence<sizeof...(Ts)>()); }
Usage:
auto some = std::make_tuple("I am good", 255, 2.1); for_each_in_tuple(some, [](const auto &x) { std::cout << x << std::endl; });
Demo.
std::index_sequence
and family are C++14 features, but they can be easily implemented in C++11 (there are many available on SO). Polymorphic lambdas are also C++14, but can be replaced with a custom-written functor.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With