在C ++中,是否可以枚举枚举(运行时或编译时(首选))并为每次迭代调用函数/生成代码?
示例用例:
enum abc
{
start
a,
b,
c,
end
}
for each (__enum__member__ in abc)
{
function_call(__enum__member__);
}
似是而非的重复:
答案 0 :(得分:55)
要添加到 @StackedCrooked 答案,您可以重载operator++
,operator--
和operator*
并具有类似迭代器的功能。
enum Color {
Color_Begin,
Color_Red = Color_Begin,
Color_Orange,
Color_Yellow,
Color_Green,
Color_Blue,
Color_Indigo,
Color_Violet,
Color_End
};
namespace std {
template<>
struct iterator_traits<Color> {
typedef Color value_type;
typedef int difference_type;
typedef Color *pointer;
typedef Color &reference;
typedef std::bidirectional_iterator_tag
iterator_category;
};
}
Color &operator++(Color &c) {
assert(c != Color_End);
c = static_cast<Color>(c + 1);
return c;
}
Color operator++(Color &c, int) {
assert(c != Color_End);
++c;
return static_cast<Color>(c - 1);
}
Color &operator--(Color &c) {
assert(c != Color_Begin);
return c = static_cast<Color>(c - 1);
}
Color operator--(Color &c, int) {
assert(c != Color_Begin);
--c;
return static_cast<Color>(c + 1);
}
Color operator*(Color c) {
assert(c != Color_End);
return c;
}
让我们测试一些<algorithm>
模板
void print(Color c) {
std::cout << c << std::endl;
}
int main() {
std::for_each(Color_Begin, Color_End, &print);
}
现在,Color
是一个常量双向迭代器。这是我在上面手动执行时编码的可重用类。我注意到它可以用于更多的枚举,所以重复相同的代码是非常乏味的
// Code for testing enum_iterator
// --------------------------------
namespace color_test {
enum Color {
Color_Begin,
Color_Red = Color_Begin,
Color_Orange,
Color_Yellow,
Color_Green,
Color_Blue,
Color_Indigo,
Color_Violet,
Color_End
};
Color begin(enum_identity<Color>) {
return Color_Begin;
}
Color end(enum_identity<Color>) {
return Color_End;
}
}
void print(color_test::Color c) {
std::cout << c << std::endl;
}
int main() {
enum_iterator<color_test::Color> b = color_test::Color_Begin, e;
while(b != e)
print(*b++);
}
实施如下。
template<typename T>
struct enum_identity {
typedef T type;
};
namespace details {
void begin();
void end();
}
template<typename Enum>
struct enum_iterator
: std::iterator<std::bidirectional_iterator_tag,
Enum> {
enum_iterator():c(end()) { }
enum_iterator(Enum c):c(c) {
assert(c >= begin() && c <= end());
}
enum_iterator &operator=(Enum c) {
assert(c >= begin() && c <= end());
this->c = c;
return *this;
}
static Enum begin() {
using details::begin; // re-enable ADL
return begin(enum_identity<Enum>());
}
static Enum end() {
using details::end; // re-enable ADL
return end(enum_identity<Enum>());
}
enum_iterator &operator++() {
assert(c != end() && "incrementing past end?");
c = static_cast<Enum>(c + 1);
return *this;
}
enum_iterator operator++(int) {
assert(c != end() && "incrementing past end?");
enum_iterator cpy(*this);
++*this;
return cpy;
}
enum_iterator &operator--() {
assert(c != begin() && "decrementing beyond begin?");
c = static_cast<Enum>(c - 1);
return *this;
}
enum_iterator operator--(int) {
assert(c != begin() && "decrementing beyond begin?");
enum_iterator cpy(*this);
--*this;
return cpy;
}
Enum operator*() {
assert(c != end() && "cannot dereference end iterator");
return c;
}
Enum get_enum() const {
return c;
}
private:
Enum c;
};
template<typename Enum>
bool operator==(enum_iterator<Enum> e1, enum_iterator<Enum> e2) {
return e1.get_enum() == e2.get_enum();
}
template<typename Enum>
bool operator!=(enum_iterator<Enum> e1, enum_iterator<Enum> e2) {
return !(e1 == e2);
}
答案 1 :(得分:42)
C ++目前不提供枚举器迭代。尽管如此,有时需要这样做。常见的解决方法是添加标记开头和结尾的值。例如:
enum Color
{
Color_Begin,
Color_Red = Color_Begin,
Color_Orange,
Color_Yellow,
Color_Green,
Color_Blue,
Color_Indigo,
Color_Violet,
Color_End
};
void foo(Color c)
{
}
void iterateColors()
{
for (size_t colorIdx = Color_Begin; colorIdx != Color_End; ++colorIdx)
{
foo(static_cast<Color>(colorIdx));
}
}
答案 2 :(得分:4)
没有一点体力劳动也不可能。如果你愿意深入研究这个领域,很多工作都可以通过宏来完成。
答案 3 :(得分:2)
扩展康拉德所说的,在“为每次迭代生成代码”的情况下,一种可能的习惯是使用包含的文件来表示枚举:
mystuff.h:
#ifndef LAST_ENUM_ELEMENT
#define LAST_ENUM_ELEMENT(ARG) ENUM_ELEMENT(ARG)
#endif
ENUM_ELEMENT(foo)
ENUM_ELEMENT(bar)
LAST_ENUM_ELEMENT(baz)
// not essential, but most likely every "caller" should do it anyway...
#undef LAST_ENUM_ELEMENT
#undef ENUM_ELEMENT
enum.h:
// include guard goes here (but mystuff.h doesn't have one)
enum element {
#define ENUM_ELEMENT(ARG) ARG,
#define LAST_ENUM_ELEMENT(ARG) ARG
#include "mystuff.h"
}
main.cpp中:
#include "enum.h"
#define ENUM_ELEMENT(ARG) void do_##ARG();
#include "mystuff.h"
element value = getValue();
switch(value) {
#define ENUM_ELEMENT(ARG) case ARG: do_##ARG(); break;
#include "mystuff.h"
default: std::terminate();
}
因此,要添加新元素“qux”,请将其添加到mystuff.h并编写do_qux
函数。您无需触摸调度代码。
当然,如果你的枚举中的值需要是特定的非连续整数,那么你最终会分别维护枚举定义和ENUM_ELEMENT(foo)
...列表,这很麻烦。
答案 4 :(得分:1)
但是,您可以定义自己的类,通过迭代实现类似枚举的功能。您可能会记得1.5天前的一个技巧,称为“类型安全枚举设计模式”。你可以做C ++等价物。
答案 5 :(得分:1)
这对我来说似乎很苛刻,但可能适合你的目的:
enum Blah {
FOO,
BAR,
NUM_BLAHS
};
// later on
for (int i = 0; i < NUM_BLAHS; ++i) {
switch (i) {
case FOO:
// foo stuff
break;
case BAR:
// bar stuff
break;
default:
// you're missing a case statement
}
}
如果您需要特殊的起始值,可以将其设为常量并将其设置在枚举中。我没有检查这是否编译,但它应该接近存在:-)。希望这会有所帮助。
我认为这种方法可能是您用例的良好平衡。如果您不需要为一堆不同的枚举类型执行此操作,并且您不想处理预处理器的东西,请使用它。只要确保你发表评论,并且可能会添加一个TODO,以便以后更改它: - )。
答案 6 :(得分:1)
我通常这样做:
enum abc
{
abc_begin,
a = abc_begin,
b,
c,
abc_end
};
void foo()
{
for( auto&& r : range(abc_begin,abc_end) )
{
cout << r;
}
}
range
完全通用,定义如下:
template <typename T>
class Range
{
public:
Range( const T& beg, const T& end ) : b(beg), e(end) {}
struct iterator
{
T val;
T operator*() { return val; }
iterator& operator++() { val = (T)( 1+val ); return *this; }
bool operator!=(const iterator& i2) { return val != i2.val; }
};
iterator begin() const { return{b}; }
iterator end() const { return{e}; }
private:
const T& b;
const T& e;
};
template <typename T>
Range<T> range( const T& beg, const T& end ) { return Range<T>(beg,end); }
答案 7 :(得分:0)
您可以使用TMP静态执行某些建议的运行时技术。
#include <iostream>
enum abc
{
a,
b,
c,
end
};
void function_call(abc val)
{
std::cout << val << std::endl;
}
template<abc val>
struct iterator_t
{
static void run()
{
function_call(val);
iterator_t<static_cast<abc>(val + 1)>::run();
}
};
template<>
struct iterator_t<end>
{
static void run()
{
}
};
int main()
{
iterator_t<a>::run();
return 0;
}
该程序的输出是:
0
1
2
参见Abrahams的第1章,Gurtovoy“C ++模板元编程”,以获得对该技术的良好处理。以这种方式对提议的运行时技术这样做的好处是,当您优化此代码时,它可以内联静态并且大致相当于:
function_call(a);
function_call(b);
function_call(c);
内联function_call以获得编译器的更多帮助。
其他枚举迭代技术的批评同样适用于此。只有当枚举从一端到一端连续递增时,此方法才有效。
答案 8 :(得分:0)
喜欢模板,但是我会记录下这个用于我的未来/其他人的用法,所以我们不会丢失以上任何一个。
为了以已知的有序方式比较事物,枚举很方便。为了对整数值的可读性,它们通常被硬编码到函数中。与预处理程序定义有些类似,但它们不会被文字替换,而是在运行时保存和访问。
如果我们有一个定义html错误代码的枚举,并且我们知道500s中的错误代码是服务器错误,那么读取这样的内容可能会更好:
enum HtmlCodes {CONTINUE_CODE=100,CLIENT_ERROR=400,SERVER_ERROR=500,NON_STANDARD=600};
if(errorCode >= SERVER_ERROR && errorCode < NON_STANDARD)
大于
if(errorCode >= 500 && errorCode < 600)
关键部分是这个,它们类似于数组! 但习惯于 投射 整数值。
简短的例子:
enum Suit {Diamonds, Hearts, Clubs, Spades};
//does something with values in the enum past "Hearts" in this case
for(int i=0;i<4;i++){
//Could also use i or Hearts, because the enum will turns these both back into an int
if( (Suit)(i) > 1 )
{
//Whatever we'd like to do with (Suit)(i)
}
}
通常,枚举也会与char *数组或字符串数组一起使用,以便您可以使用关联值打印一些消息。通常它们只是在枚举中具有相同值集的数组,如下所示:
char* Suits[4] = {"Diamonds", "Hearts", "Clubs", "Spades"};
//Getting a little redundant
cout << Suits[Clubs] << endl;
//We might want to add this to the above
//cout << Suits[(Suit)(i)] << endl;
当然,创建一个处理枚举迭代的泛型类就更好了,就像上面的答案一样。