Any better solution than manually writing a utility like this?
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 ) );
}
To be used like this:
std::tuple<char, int, double> tt;
TupleForEach( tt, (boost::lambda::_1 = 5) );
A C++ tuple is a container that can store multiple values of multiple types in it. We can access the elements of the tuple using std::get(), but std::get() always takes a constant variable parameter, so we can not simply iterate through it using a loop.
We can iterate over tuples using a simple for-loop. We can do common sequence operations on tuples like indexing, slicing, concatenation, multiplication, getting the min, max value and so on.
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. This way the original queue remains untouched, but its copy becomes empty.
Class template std::tuple is a fixed-size collection of heterogeneous values. It is a generalization of std::pair.
Even though there are several answers provided in a previous, related question (and the one you provide yourself), my initial impression is that the need to iterate over the tuple may be a reflection of a poor design.
As you know, the reason why we cannot iterate over a std::tuple
using standard C++ algorithms is because std::tuple
does not fulfill the Container
concept. And, precisely, it does not fulfill such concept because std::tuple
s do not have a 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 an standard container (e.g., std::vector<std::shared_ptr<BaseClass>>
). This gave you a quick gain. But that also means that you voluntarily gave up the advantages of Container
s.
It may work, but it somehow feels forced and unnatural: if you need container semantics, why not use a container? If you need polymorphic semantics, why not use a polymorphic type?
Probably I'm exaggerating, but this is my initial impression.
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