在我的程序中,我想使用显示错误消息的断言.除了众所周知的C和C++的解决方法之外,还有BOOST提供的"真实"解决方案BOOST_ASSERT_MSG( expr, msg )(另请参见带有消息的assert())
但是静态消息对我来说还不够,我还想有时候显示失败的变量,例如在类似的情况下
BOOST_ASSERT_MSG( length >= 0, "No positive length found! It is " << length )
正如您所看到的,我想将消息"string"格式化为stringstream或者ostream允许我轻松地显示自定义类型(假设我已经定义了相关的格式化函数).
这里的问题是BOOST_ASSERT_MSG默认情况下要求char const *不兼容.
有没有办法重新定义/重载assertion_failed_msg(),使用流作为消息将起作用?怎么样?
(我的天真方法失败了,因为编译器首先要对operator<<("foo",bar)消息本身做一个...)
您可以定义自己的宏
#define ASSERT_WITH_MSG(cond, msg) do \
{ if (!(cond)) { std::ostringstream str; str << msg; std::cerr << str.str(); std::abort(); } \
} while(0)
实现这一目标相对微不足道.
BOOST_ASSERT_MSG( length >= 0, (std::stringstream() << "No positive length found! It is " << length).str().c_str() )