我将如何遍历多个枚举。
我有点想在骨架中包含枚举
不确定如何构造枚举以将其放入这样的容器中
那还不确定我如何循环获取每种类型
答案 0 :(得分:0)
简短的答案是你不能。至少在C ++中还没有。
要做您要描述的事情,您需要反思。反射使您可以在运行时以动态方式遍历对象。
C#/。net提供了这一点。这是C#中的示例。
enum MyEnum { Test, Test1, Test2, Another, One, Bites, The, Dust }
foreach (var value in typeof(MyEnum).GetEnumValues()) {
WriteLine(value.ToString());
}
我不确定C ++是否会采用反射形式,无论是这种形式还是其他形式。
很抱歉,如果这不是您想要的全部答案。
答案 1 :(得分:0)
我有一个基于元组的元编程方法
#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;
});
}
P.S。是的,我们需要使用C ++(可能是C ++ 23)进行编译时反射