强制使用强类型检查在C(对于类型定义类型严格) [英] Enforce strong type checking in C (type strictness for typedefs)
问题描述
有没有办法强制执行相同类型的类型定义明确的转换?我已经处理UTF8,有时我感到困惑与指数的字符数和字节数。因此,它是很好,有一些类型定义:
Is there a way to enforce explicit cast for typedefs of the same type? I've to deal with utf8 and sometimes I get confused with the indices for the character count and the byte count. So it be nice to have some typedefs:
typedef unsigned int char_idx_t;
typedef unsigned int byte_idx_t;
在增加,你需要在它们之间进行明确的转换:
With the addition that you need an explicit cast between them:
char_idx_t a = 0;
byte_idx_t b;
b = a; // compile warning
b = (byte_idx_t) a; // ok
我知道,这样的功能不存在C,但也许你知道一个把戏或编译器扩展(preferable GCC)的做到这一点。
I know that such a feature doesn't exist in C, but maybe you know a trick or a compiler extension (preferable gcc) that does that.
修改
我还是真的不喜欢一般的匈牙利命名法。我不能使用它,因为项目编码约定的这个问题,但我现在用它在另一个类似的情形,在那里也是类型相同,含义非常相似。我不得不承认:它帮助。我永远不会去和一个开始宣布每个整数i,但在乔尔的榜样重叠类型,它可以挽救生命。
EDIT I still don't really like the Hungarian notation in general. I couldn't use it for this problem because of project coding conventions, but I used it now in another similar case, where also the types are the same and the meanings are very similar. And I have to admit: it helps. I never would go and declare every integer with a starting "i", but as in Joel's example for overlapping types, it can be life saving.
推荐答案
您可以这样做:
typedef struct {
unsigned int c_idx;
} char_idx;
typedef struct {
unsigned int b_idx;
} byte_idx;
然后,当你在使用每个你会看到:
Then you would see when you are using each:
char_idx a;
byte_idx b;
b.b_idx = a.c_idx;
现在更清楚,它们是不同的类型,但仍然会进行编译。
Now it is more clear that they are different types but would still compile.
这篇关于强制使用强类型检查在C(对于类型定义类型严格)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!