有没有一种在 C 中强制类型不兼容的好方法? [英] Is there a good way to force type incompatibility in C?
问题描述
出于类型检查的目的,我想在
For purposes of type checking I would like to define a function on the lines of
void myfunc(type1 a, type2 b)
{
...
}
其中 type1
和 type2
都被定义为 uint8_t
.到目前为止一切顺利,但出于理智和检查目的(想想 DbC),我想防止使用 type2
值作为第一个参数或 type1
调用函数第二.可悲的是,C 的隐式类型转换在这里对我不利.有人知道方法吗?
where type1
and type2
are both typedefed to uint8_t
. So far so good, but for sanity and checking purposes (think DbC) I would like to prevent the function being called with a type2
value for the first parameter or a type1
for the second. Sadly, C's implicit typecasting is against me here. Does anyone know of a way?
推荐答案
您可以将这两种类型包装在一个 Struct 中.
You could wrap the two types in a Struct.
typedef struct {
uint8_t data;
} type1;
typedef struct {
uint8_t data;
} type2;
我不喜欢它,因为你现在必须使用 a.data 而不是
I don't like it because you now have to use a.data instead of a
这篇关于有没有一种在 C 中强制类型不兼容的好方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!