[英]Find out if a typedef defines a specific type in C
我必须在 C 中实现一个链表数据结构。在"linked_list.h"
头文件中,我有以下行:
typedef int ListDataType;
我的问题是,如果ListDataType
不等于int
,我该如何终止程序? 我知道预处理器无法阻止我的程序在不满足此要求的情况下编译(因为它对typedef
一无所知)。
我用 C11 编码,我知道_Generic
关键字。 我怎样才能避免写如下这样的东西?
{
ListDataType q;
const bool kListDataTypeIsNotInt = _Generic(q, int: false, default: true);
if (kListDataTypeIsNotInt) {
print_error_message_and_exit("list data types other than int are not supported");
}
}
我应该改用宏( #define LIST_DATA_TYPE int
)吗?
您代码中的变量将被优化掉,我强烈怀疑此代码在优化后将是 100% 编译时。
尽管如此,如果你不确定,你可以通过引入一个宏和一个静态断言来稍微调整它:
#define IS_INT(q) _Generic((q), int: true, default: false)
...
ListDataType q;
_Static_assert(IS_INT(q), "list data types other than int are not supported");
这是 100% 编译时间和良好实践。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.