C++自 C++11 起支持 static_assert 编译时断言,如:

1
2
static_assert ( bool_constexpr , message )    (C++11 起)
static_assert ( bool_constexpr ) (C++17 起)

若编译器不支持 C++11(经测试 VS2010 已经支持static_assert),可以使用下面方式来实现编译断言:

1
#define COMPILE_ASSERT(expression) switch (0) {case 0: case expression:;}

使用方法:

1
COMPILE_ASSERT(1 != 1);