使用C中的枚举来实现类型安全是有问题的,因为它们基本上只是整数.实际上,枚举常量被定义为int标准的类型.
为了实现一点类型的安全性我用这样的指针做了一些技巧:
typedef enum
{
BLUE,
RED
} color_t;
void color_assign (color_t* var, color_t val)
{
*var = val;
}
Run Code Online (Sandbox Code Playgroud)
因为指针具有比值更严格的类型规则,所以这会阻止这样的代码:
int x;
color_assign(&x, BLUE); // compiler error
Run Code Online (Sandbox Code Playgroud)
但它不会阻止这样的代码:
color_t color;
color_assign(&color, 123); // garbage value
Run Code Online (Sandbox Code Playgroud)
这是因为枚举常量基本上只是一个int,可以隐式赋值给枚举变量.
有没有办法编写这样的函数或宏color_assign,即使对于枚举常量也可以实现完整的类型安全性?