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

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

问题描述

Hallo!

我正在寻找一种方法来添加自定义消息到assert语句。
我发现了这个问题 http://stackoverflow.com/questions/3692954/add- custom-messages-in-assert ,但消息是静态的。我想做这样的事情:

I'm looking for a way to add custom messages to assert statements. I found this questions http://stackoverflow.com/questions/3692954/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 is 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.

基本上,它可以看起来像这样:

Basically, it can look like this:

#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);

这比你的用法简单一点,因为你不需要stringify x was 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天全站免登陆