是否有满足C99标准的static_assert替代品? [英] Is there a static_assert replacement which satisfies the C99 standard?
问题描述
我一直在尝试实现类似于C ++ 11标准中定义的 static_assert
的方法.主要问题是C ++编译器如何将传递到 static_assert
的文本消息作为 const char *
编写?我可以让编译器编写诸如 A_is_not_POD
之类的消息.这就是我所拥有的:
I have been trying to implement a method similar to static_assert
which is defined in the C++11 standard. The main problem is how does the C++ compiler write the text message being passed to static_assert
as a const char*
? I can get the compiler to write a message like A_is_not_POD
. This is what I have:
#define MY_STATIC_ASSERT(condition, name) \
typedef char name[(condition) ? 1 : -1];
但是让编译器编写类似错误:A不是POD."
有什么建议吗?
But it would be quite nice to get the compiler to write something like "Error: A is not POD."
Any suggestions?
推荐答案
我不确定我是否理解问题,但是C11具有 _Static_assert(condition,errmessage)
.在C99中,缺少此功能,但是根据编译器的不同,有可能进行仿真.例如.for gcc(不幸的是clang不支持attribute(error))
Not sure i understand question, but C11 have _Static_assert(condition, errmessage)
. In C99 this functionality was missing but, depending on compiler, it could be possible to emulate. E.g. for gcc (unfortulately clang doesn't support attribute(error))
#define MY_STATIC_ASSERT(cnd, descr) ({ \
extern int __attribute__ ((error("static assert failed: (" #cnd ") (" #descr ")"))) \
compile_time_check(void); \
((cnd) ? 0 : compile_time_check()), 0; \
})
这篇关于是否有满足C99标准的static_assert替代品?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!