|
Boost Users : |
Subject: Re: [Boost-users] [Range][Iterator] iterate over an enumeration?
From: Nathan Ridge (zeratul976_at_[hidden])
Date: 2013-01-29 16:46:13
> I'd like to make it easy to do a BOOST_FOREACH for every value in an enumeration. I tried
> enum E { E_First, ⯠, E_Last };
> boost::counting_range(E_First, E_Last)
> but got compiler template barf.
>
> Can someone suggest a good way to do this?
I've accomplished this using a combination of Boost.Range and Boost.Phoenix, as follows:
template <typename EnumT>
auto enum_range(EnumT first, EnumT last)
{
using boost::counting_range;
using boost::adaptors::transformed;
using boost::phoenix::static_cast_;
using boost::phoenix::arg_names::arg1;
return counting_range((int)first, (int)last) | transformed(static_cast_<EnumT>(arg1));
}
Then the usage is:
BOOST_FOREACH(E e, enum_range(E_First, E_Last))
...
I've omitted the return type of the enum_range function above. If you use C++11, you can
get the compiler to deduce it using decltype and late-specified return types (this is what I
do), otherwise you can look up the documentation of the various Boost constructs involved
and write down the return type directly (it'll be boost::transformed_range< /* something
involving phoenix::static_cast_ */, /* something involving counting_range */>).
Hope that helps!
Regards,
Nate
Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net