Is there an elegant solution to use common code to iterate through hash_map/unordered_map and list/vector collections?
An example:
template<typename collection>
class multicast
{
public:
typedef collection collection_type;
private:
collection_type& m_channels;
public:
multicast(collection_type& channels) : m_channels(channels) { }
void operator ()(const buffer::ptr& head, const buffer::ptr& cnt)
{
for each(collection_type::value_type& ch in m_channels)
ch->send(head, cnt); /* this is where the magic should happen? */
}
}
This code obviously fails to compile when collection_type is unordered_map since collection_type::value_type is a pair so the code that access the actual value should be different: ch.second->send(head, cnt) instead of ch->send(head, cnt). So what would be the most elegant way to get rid of key part when it is not needed?
Yes:
Alternatively:
If neither range-based
fornorautoare available, you could write a template which takes a containerCand useC::value_typeandC::iterator; or you could make a template which accepts a pair of iterators of typeIterand usesstd::iterator_traits<Iter>::value_typefor the element value type.Thirdly, you can use
for_eachand a lambda:To accommodate for both single-element and pair-element containers, you can build a little wrapper:
Now you can use
get_value(x)orget_value(*it)to get the value only.