How to iterate through std :: tuple?

Any better solution than manually recording such a utility?

template < size_t > struct SizeT { }; template < typename TupleType, typename ActionType > inline void TupleForEach( TupleType& tuple, ActionType action ) { TupleForEach( tuple, action, SizeT<std::tuple_size<TupleType>::value>() ); } template < typename TupleType, typename ActionType > inline void TupleForEach( TupleType& tuple, ActionType action, SizeT<0> ) { } template < typename TupleType, typename ActionType, size_t N > inline void TupleForEach( TupleType& tuple, ActionType action, SizeT<N> ) { TupleForEach( tuple, action, SizeT<N-1>() ); action( std::get<N-1>( tuple ) ); } 

Used as follows:

 std::tuple<char, int, double> tt; TupleForEach( tt, (boost::lambda::_1 = 5) ); 
+6
source share
1 answer

Despite the fact that there are several answers in the previous related question (and the one you provide yourself), my initial impression is that you need to iterate over a Tuple can be a reflection of poor design.

As you know, the reason we cannot iterate over std::tuple using standard C ++ algorithms is because std::tuple does not fulfill the Container concept . And, precisely, it does not fulfill such a concept, because std::tuple does not have value_type (they are heterogeneous). I know that you used a tuple because you did not want to create your own polymorphic type and store it in a standard container (for example, std::vector<std::shared_ptr<BaseClass>> ). This gave you a quick win. But it also means that you voluntarily abandoned the benefits of Container s.

It might work, but it somehow seems forced and unnatural: if you need container semantics, why not use a container? If you need polymorphic semantics, why not use a polymorphic type?

I may be exaggerating, but this is my initial impression.

+1
source

Source: https://habr.com/ru/post/951425/


All Articles