枚举可以用作(或转换为) C++20范围吗?
我正在考虑以下用例,cartesian_product()是C++23的不幸之处:
#include <algorithm>
using namespace std::ranges;
enum Fruit{APPLE, STRAWBERRY, COCONUT};
enum Vegetable{CARROT,POTATOE};
for (auto [fruit, vegetable] : views::cartesian_product(Fruit, Vegetable))
{
...
}发布于 2022-09-12 15:22:26
您可以这样做,只是需要一个库的帮助才能将枚举转换为一系列枚举数名称。其中一个类库是Boost.Describe。
#include <array>
#include <boost/describe.hpp>
#include <fmt/ranges.h>
enum Fruit{APPLE, STRAWBERRY, COCONUT};
enum Vegetable{CARROT,POTATO};
BOOST_DESCRIBE_ENUM(Fruit, APPLE, STRAWBERRY, COCONUT);
BOOST_DESCRIBE_ENUM(Vegetable, CARROT, POTATO);
template<class E>
constexpr auto enum_names() {
return []<template <class...> class L, class... T>(L<T...>)
-> std::array<char const*, sizeof...(T)>
{
return {T::name...};
}(boost::describe::describe_enumerators<E>());
}
int main() {
// prints fruits=["APPLE", "STRAWBERRY", "COCONUT"] vegetables=["CARROT", "POTATO"]
fmt::print("fruits={} vegetables={}\n", enum_names<Fruit>(), enum_names<Vegetable>());
}https://stackoverflow.com/questions/73679033
复制相似问题