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

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

问题描述

你好!

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

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.

基本上,它可以是这样的:

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

仅当未定义无调试宏 NDEBUG 时,才会定义 ASSERT 宏.

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

然后你会像这样使用它:

Then you’d use it like this:

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

这比您的用法简单一点,因为您不需要显式字符串化 "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天全站免登陆