用C类型安全枚举? [英] Typesafe enums in C?

查看:135
本文介绍了用C类型安全枚举?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个以上的枚举,例如:

If I have more than one enum, eg:

 enum Greetings{ hello, bye, how };

 enum Testing { one, two, three };

我怎么能执行正确的用法枚举
举例来说,我不希望有人用时,他们应该使用你好 有一个更好的调试和可读性。

How can I enforce the usage of the correct enum? For example, I don't want someone to use hello when they should be using one for better debugging and readability.

推荐答案

在C,您可以伪造其与样板code。

In C, you can fake it with boilerplate code.

typedef enum { HELLO_E, GOODBYE_E } greetings_t;
struct greetings { greetings_t greetings; };
#define HELLO ((struct greetings){HELLO_E})
#define GOODBYE ((struct greetings){GOODBYE_E})

typedef enum { ONE_E, TWO_E } number_t;
struct number { number_t number; };
#define ONE ((struct number){ONE_E})
#define TWO ((struct number){TWO_E})

void takes_greeting(struct greetings g);
void takes_number(struct number n);

void test()
{
    takes_greeting(HELLO);
    takes_number(ONE);

    takes_greeting(TWO);
    takes_number(GOODBYE);
}

这不应该承担任何开销,并且产生的错误而不是警告:

This should not incur any overhead, and produces errors instead of warnings:


$ gcc -c -std=c99 -Wall -Wextra test2.c
test2.c: In function ‘test’:
test2.c:19: error: incompatible type for argument 1 of ‘takes_greeting’
test2.c:20: error: incompatible type for argument 1 of ‘takes_number’

请注意,我没有使用GNU的扩展,并且不会产生假警告。仅错误。另外请注意,我使用一个版本的GCC那是旧如粪土,

Notice that I'm not using GNU extensions, and no spurious warnings are generated. Only errors. Also note that I'm using a version of GCC that's as old as dirt,


$ gcc --version
powerpc-apple-darwin9-gcc-4.0.1 (GCC) 4.0.1 (Apple Inc. build 5493)
Copyright (C) 2005 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

这应该与C99的复合文字支持任何编译器的工作。

This should work with any compiler with support for C99's compound literals.

这篇关于用C类型安全枚举?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆