遍历多个枚举 [英] looping over multiple enums
本文介绍了遍历多个枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我将如何遍历多个枚举。
How would i loop over multiple enums.
我有点想将枚举包含在骨架中
I kind of want to have the enums inside skeleton
不十分确定如何构造我的枚举以将其放入这样的容器中
Not really sure on how to construct my enums to have them in a container like this
然后不确定是否可以循环获取每种类型
Then not really sure how i could loop it to get each of the types
推荐答案
我有一个基于元组的元编程方法
I got a meta-programming approach based on tuple
#include <tuple>
#include <type_traits>
#include <utility>
#include <iostream>
struct foo_enumerator {
enum class foo {
ONE = 0 ,
TWO = 1,
THREE = 2
};
static constexpr auto reflect = std::make_tuple(
foo::ONE,
foo::TWO,
foo::THREE);
};
struct bar_enumerator {
enum class bar {
FOUR = 4,
FIVE = 5,
SIX = 6
};
static constexpr auto reflect = std::make_tuple(
bar::FOUR,
bar::FIVE,
bar::SIX);
};
// a tuple for_each implementation
// can be replaced with something else, like boost hana for_each for example
namespace detail {
// workaround for default non-type template arguments
template<std::size_t I>
using index_t = std::integral_constant<std::size_t, I>;
// process the `From::value`-th element
template<typename FromIndex,
typename ToIndex,
typename Tuple,
typename UnaryFunction>
struct for_each_t {
constexpr UnaryFunction&& operator()(Tuple&& t, UnaryFunction&& f) const
{
std::forward<UnaryFunction>(f)(
std::get<FromIndex::value>(std::forward<Tuple>(t)));
return for_each_t<index_t<FromIndex::value + 1>,
ToIndex,
Tuple,
UnaryFunction>()(
std::forward<Tuple>(t), std::forward<UnaryFunction>(f));
}
};
// specialization for empty tuple-likes
template<typename FromIndex, typename Tuple, typename UnaryFunction>
struct for_each_t<FromIndex, index_t<0>, Tuple, UnaryFunction> {
constexpr UnaryFunction&& operator()(Tuple&&, UnaryFunction&& f) const
{
return std::forward<UnaryFunction>(f);
}
};
// specialization for last element
template<typename ToIndex, typename Tuple, typename UnaryFunction>
struct for_each_t<index_t<ToIndex::value - 1>, ToIndex, Tuple, UnaryFunction> {
constexpr UnaryFunction&& operator()(Tuple&& t, UnaryFunction&& f) const
{
std::forward<UnaryFunction>(f)(
std::get<ToIndex::value - 1>(std::forward<Tuple>(t)));
return std::forward<UnaryFunction>(f);
}
};
} // namespace detail
template<typename Tuple, typename UnaryFunction>
constexpr UnaryFunction for_each(Tuple&& t, UnaryFunction&& f)
{
return detail::for_each_t<detail::index_t<0>,
detail::index_t<std::tuple_size<
std::remove_reference_t<Tuple>
>::value>,
Tuple,
UnaryFunction>()(
std::forward<Tuple>(t), std::forward<UnaryFunction>(f));
}
int main(int argc, const char** argv)
{
constexpr auto all = std::tuple_cat( foo_enumerator::reflect, bar_enumerator::reflect );
for_each(all, [](auto e_value) {
std::cout << "Enumeration value: " << static_cast<unsigned int>(e_value) << std::endl;
});
}
这篇关于遍历多个枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文