P213
要点
头文件
#include <boost/assert.hpp>
- 默认情况下BOOST_ASSERT宏等同于assert宏,断言表达式为真,即:
#define BOOST_ASSERT(expr) assert(expr)。如果参数expr表达式值为true,那么断言成立,程序会继续向下执行,否则断言会引发一个异常。 BOOST_ASSERT宏仅会在debug模式下生效。
扩展用法 P215
如果在头文件
<boost/assert.hpp>
之前定义了宏BOOST_ENABLE_ASSERT_HANDLE,这将导致BOOST_ASSERT的行为发生改变:
它将不再等同于assert宏,断言的表达式在debug、release模式下都会被求值。如果断言失败,会发生一个断言失败的函数调用boost::assertion_failed()。
- BOOST_VERIFY P216
- static_assert->BOOST_STATIC_ASSERT
下面的代码定义了一个简单的模板函数my_min,出于某种目的,它仅支持short或者char的类型:
#include <boost/static_assert.hpp> template<typename T> T my_min(T a,T b) { BOOST_STATIC_ASSERT(sizeof(T) < sizeof(int)); //静态断言 return a<b?a:b; } int main() { cout << my_min((short)1,(short)3); //OK cout << my_min(1L,3L); //编译期错误 }