静态断言
静态断言用来在编译阶段发现不符合预期的问题,并给出自定义的错误信息。
_Static_assert
是 C11 中引入的关键字。 static_assert
是 C11 中引入的宏,它映射到 _Static_assert
关键字。它们可用于全局或函数范围。
C++11标准新引入的static_assert
功能可以实现静态断言。
static_assert
相关代码在 C 和 C++ 中均适用。
PG中静态断言宏,支持所有版本C/C++
/*
* Macros to support compile-time assertion checks.
*
* If the "condition" (a compile-time-constant expression) evaluates to false,
* throw a compile error using the "errmessage" (a string literal).
*
* gcc 4.6 and up supports _Static_assert(), but there are bizarre syntactic
* placement restrictions. Macros StaticAssertStmt() and StaticAssertExpr()
* make it safe to use as a statement or in an expression, respectively.
* The macro StaticAssertDecl() is suitable for use at file scope (outside of
* any function).
*
* Otherwise we fall back on a kluge that assumes the compiler will complain
* about a negative width for a struct bit-field. This will not include a
* helpful error message, but it beats not getting an error at all.
*/
#ifndef __cplusplus
#ifdef HAVE__STATIC_ASSERT
#define StaticAssertStmt(condition, errmessage) \
do { _Static_assert(condition, errmessage); } while(0)
#define StaticAssertExpr(condition, errmessage) \
((void) ({ StaticAssertStmt(condition, errmessage); true; }))
#define StaticAssertDecl(condition, errmessage) \
_Static_assert(condition, errmessage)
#else /* !HAVE__STATIC_ASSERT */
#define StaticAssertStmt(condition, errmessage) \
((void) sizeof(struct { int static_assert_failure : (condition) ? 1 : -1; }))
#define StaticAssertExpr(condition, errmessage) \
StaticAssertStmt(condition, errmessage)
#define StaticAssertDecl(condition, errmessage) \
extern void static_assert_func(int static_assert_failure[(condition) ? 1 : -1])
#endif /* HAVE__STATIC_ASSERT */
#else /* C++ */
#if defined(__cpp_static_assert) && __cpp_static_assert >= 200410
#define StaticAssertStmt(condition, errmessage) \
static_assert(condition, errmessage)
#define StaticAssertExpr(condition, errmessage) \
({ static_assert(condition, errmessage); })
#define StaticAssertDecl(condition, errmessage) \
static_assert(condition, errmessage)
#else /* !__cpp_static_assert */
#define StaticAssertStmt(condition, errmessage) \
do { struct static_assert_struct { int static_assert_failure : (condition) ? 1 : -1; }; } while(0)
#define StaticAssertExpr(condition, errmessage) \
((void) ({ StaticAssertStmt(condition, errmessage); }))
#define StaticAssertDecl(condition, errmessage) \
extern void static_assert_func(int static_assert_failure[(condition) ? 1 : -1])
#endif /* __cpp_static_assert */
#endif /* C++ */
参考:
https://docs.microsoft.com/zh-cn/cpp/cpp/static-assert?view=msvc-170
https://docs.microsoft.com/zh-cn/cpp/c-language/static-assert-c?view=msvc-160