如何验证在C宏类型 [英] How to verify a type in a C macro

查看:195
本文介绍了如何验证在C宏类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在思考的方式来验证C宏类型,到目前为止,我想出最好的办法是这样的:

I have been thinking about ways to validate types in C macros and so far the best way that I have come up with is this:

#define ASSERT_PTYPE(TYPE, VALUE) (0 && (*(int (*)(TYPE*))0)(VALUE))

这显然需要一个类型名称和一个指针类型。类似的ASSERT_TYPE宏可以进行为好。这似乎与海湾合作委员会的工作非常好。它甚至给出的类型不匹配的情况下非常有用的错误消息。问题是,我不能完全肯定,这是有效的C或为此事的最佳途径。

This obviously expects a type name and a pointer to that type. A similar ASSERT_TYPE macro can be made as well. This seems to work quite well with GCC. It even gives a very helpful error message in the case that the types do not match. The problems are that I am not completely certain that this is valid C or the best way for that matter.

据我了解标准的说,你可以投一个函数指针,但调用投函数指针的结果是不确定的。在这种情况下,这是不可能的,以在运行时调用该函数。那是足够好或不标准意味着你甚至不能写code,它不能被称为调用转换函数?

As I understand it the standard says that you can cast a function pointer, but the result of calling the cast function pointer is undefined. In this case it is impossible for the function to be called at runtime. Is that good enough or does the standard mean that you cannot even write code that cannot be called that calls the cast function?

推荐答案

通过C99和复合文字,你可以这样做

With C99 and compound literals you can do something like

#define ASSERT_TYPE(TYPE, VALUE) ((TYPE){ 0 } = (VALUE))

这确保了是分配兼容键入。这位前pression返回由于分配的右值。

This ensures that VALUE is assignment compatible to TYPE. The expression returns an rvalue because of the assignment.

复合文字的功能范围,以及在文件范围内工作,任何像样的编译器应该优化所创建出的方式额外的对象。

Compound literals work in function scope as well as in file scope and any decent compiler should optimize the extra object that is created out of the way.

加入键入在微距可以是任何有效的类型名称,如指针双* ,结构或联合结构TOTO ,除了阵列。如阵列式双[4] 不会因为分配的工作。使用指针
阵列双(*)[4] 来代替,例如在

Addition: TYPE in that macro can be any valid type name, e.g pointer double*, struct or union struct toto, besides arrays. Array type such as double[4] wouldn't work because of the assignment. Use pointer to array double(*)[4] instead, e.g as in

double A[4];
(*ASSERT_TYPE(double(*)[4], &A))

在第二行又是类型的左值双击[4] 是编译时检查该属性。

这篇关于如何验证在C宏类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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