前阵子听说visual studio 2010支持c++四个新特性,其一就是静态断言。今天查boost的时候无意中又浏览了一下静态断言的实现。我从来没用过静态断言,不过从这看来,静态断言从库实现到变成语言特性,说明它是很有用的。这激发了我在工作项目中使用静态断言的欲望。因为项目是C代码,我估计之前应该有人用宏等技巧实现过。google之:
//=================================================================
1.传说在linux内核中使用,原理是-1大小数组报错
#define BUILD_BUG_ON(condition) ((void)sizeof(char[1 - 2*!!(condition)]))
//=================================================================
2.原理也是-1大小数组报错#define STATIC_ASSERT(x) \
do { \
const static char dummy[(x)?1:-1] = {0};\
} while(0)
//=================================================================
3.这个貌似比较复杂,包括负位域、数组重定义....
#ifdef __GNUC__
#define STATIC_ASSERT_HELPER(expr, msg) \
(!!sizeof \ (struct { unsigned int STATIC_ASSERTION__##msg: (expr) ? 1 : -1; }))
#define STATIC_ASSERT(expr, msg) \
extern int (*assert_function__(void)) [STATIC_ASSERT_HELPER(expr, msg)]
#else
#define STATIC_ASSERT(expr, msg) \
extern char STATIC_ASSERTION__##msg[1]; \
extern char STATIC_ASSERTION__##msg[(expr)?1:2]
#endif /* #ifdef __GNUC__ */
//=================================================================
4.这个则是枚举无穷大保错
#define ASSERT_CONCAT_(a, b) a##b
#define ASSERT_CONCAT(a, b) ASSERT_CONCAT_(a, b)
/* These can't be used after statements in c89. */
#ifdef __COUNTER__
/* microsoft */
#define STATIC_ASSERT(e,m) \
enum { ASSERT_CONCAT(static_assert_, __COUNTER__) = 1/(!!(e)) }
#else
/* This can't be used twice on the same line so ensure if using in headers
* that the headers are not included twice (by wrapping in #ifndef...#endif)
* Note it doesn't cause an issue when used on same line of separate modules
* compiled with gcc -combine -fwhole-program. */
#define STATIC_ASSERT(e,m) \
enum { ASSERT_CONCAT(assert_line_, __LINE__) = 1/(!!(e)) }
#endif
显然,有些只能在global中使用,有些只能在函数中使用;用古老的VC6测试了下,方法3比较通用。假期后上班用CCS测试下,看看哪个好使,早点运用在工程中
阅读(3792) | 评论(0) | 转发(0) |