在C中,枚举类型与整数无法区分.很烦人.
我能想到的唯一前进方法是使用结构而不是枚举的kludgy解决方法.结构是生成性的,因此数以千计是截然不同的.如果调用约定合理(AMD64),则不会有运行时开销.
这是一个使用结构的示例,它可以获得您想要的编译时错误.Kludgy,但它有效:
#includeenum hundred_e { VALUE_HUNDRED_A = 100, VALUE_HUNDRED_B }; enum thousand_e { VALUE_THOUSAND_A = 1000, VALUE_THOUSAND_B }; struct hundred { enum hundred_e n; }; struct thousand { enum thousand_e n; }; const struct hundred struct_hundred_a = { VALUE_HUNDRED_A }; const struct hundred struct_hundred_b = { VALUE_HUNDRED_B }; const struct thousand struct_thousand_a = { VALUE_THOUSAND_A }; const struct thousand struct_thousand_b = { VALUE_THOUSAND_B }; void print_hundred(struct hundred foo) { switch (foo.n) { case VALUE_HUNDRED_A: printf("hundred:a\n"); break; case VALUE_HUNDRED_B: printf("hundred:b\n"); break; default: printf("hundred:error(%d)\n", foo.n); break; } } void print_thousand(struct thousand bar) { switch (bar.n) { case VALUE_THOUSAND_A: printf("thousand:a\n"); break; case VALUE_THOUSAND_B: printf("thousand:b\n"); break; default: printf("thousand:error(%d)\n", bar.n); break; } } int main(void) { print_hundred(struct_hundred_a); print_hundred(struct_thousand_a); /* Want a compile error here */ print_thousand(struct_thousand_a); print_thousand(struct_hundred_a); /* Want a compile error here */ return 0; }