添加消息以断言 [英] Adding message to assert

查看:121
本文介绍了添加消息以断言的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Hallo!

我正在寻找一种将自定义消息添加到assert语句的方法。
我发现这个问题添加自定义消息在断言?,但消息是静态在那里我想做这样的事情:

I'm looking for a way to add custom messages to assert statements. I found this questions Add custom messages in assert? but the message is static there. I want to do something like this:

assert((0 < x) && (x < 10), std::string("x was ") + myToString(x));

当断言失败时,我想要正常输出加例如x为100。

When the assertion fails I want the normal output plus for example "x was 100".

推荐答案

你在这里不幸。最好的方法是定义你自己的 assert 宏。

You are out of luck here. The best way is to define your own assert macro.

基本上可以这样看:

#ifndef NDEBUG
#   define ASSERT(condition, message) \
    do { \
        if (! (condition)) { \
            std::cerr << "Assertion `" #condition "` failed in " << __FILE__ \
                      << " line " << __LINE__ << ": " << message << std::endl; \
            std::terminate(); \
        } \
    } while (false)
#else
#   define ASSERT(condition, message) do { } while (false)
#endif

这将只定义 ASSERT 无调试宏 NDEBUG 未定义。

This will define the ASSERT macro only if the no-debug macro NDEBUG isn’t defined.

然后,您可以使用它:

ASSERT((0 < x) && (x < 10), "x was " << x);

哪些比您的使用更简单,因为您不需要使用x是 x 明确地说,这是由宏隐含地完成的。

Which is a bit simpler than your usage since you don’t need to stringify "x was " and x explicitly, this is done implicitly by the macro.

这篇关于添加消息以断言的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆