C++ 在断言中添加自定义消息?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3692954/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 13:29:00  来源:igfitidea点击:

Add custom messages in assert?

c++assert

提问by Killrazor

Is there a way to add or edit the message thrown by assert? I'd like to use something like

有没有办法添加或编辑断言抛出的消息?我想使用类似的东西

assert(a == b, "A must be equal to B");

Then, the compiler adds line, timeand so on...

然后,编译器添加linetime等......

Is it possible?

是否可以?

回答by zneak

A hack I've seen around is to use the &&operator. Since a pointer "is true" if it's non-null, you can do the following without altering the condition:

我见过的一个技巧是使用&&操作符。由于指针如果不为空则“为真”,因此您可以在不改变条件的情况下执行以下操作:

assert(a == b && "A is not equal to B");

Since assertshows the condition that failed, it will display your message too. If it's not enough, you can write your own myAssertfunction or macro that will display whatever you want.

由于assert显示失败的条件,它也会显示您的消息。如果这还不够,您可以编写自己的myAssert函数或宏来显示您想要的任何内容。

回答by Andrei Bozantan

Another option is to reverse the operands and use the comma operator. You need extra parentheses so the comma isn't treated as a delimiter between the arguments:

另一种选择是反转操作数并使用逗号运算符。您需要额外的括号,以便逗号不被视为参数之间的分隔符:

assert(("A must be equal to B", a == b));

(this was copied from above comments, for better visibility)

(这是从上面的评论中复制的,以获得更好的可见性)

回答by Eugene Magdalits

Here's my version of assert macro, which accepts the message and prints everything out in a clear way:

这是我的 assert 宏版本,它接受消息并以清晰的方式打印出所有内容:

#include <iostream>

#ifndef NDEBUG
#   define M_Assert(Expr, Msg) \
    __M_Assert(#Expr, Expr, __FILE__, __LINE__, Msg)
#else
#   define M_Assert(Expr, Msg) ;
#endif

void __M_Assert(const char* expr_str, bool expr, const char* file, int line, const char* msg)
{
    if (!expr)
    {
        std::cerr << "Assert failed:\t" << msg << "\n"
            << "Expected:\t" << expr_str << "\n"
            << "Source:\t\t" << file << ", line " << line << "\n";
        abort();
    }
}

Now, you can use this

现在,你可以使用这个

M_Assert(ptr != nullptr, "MyFunction: requires non-null argument");

And in case of failure you will get a message like this:

如果失败,您将收到如下消息:

Assert failed: ?MyFunction: requires non-null argument

Expected: ptr != nullptr

Source: C:\MyProject\src.cpp, line 22

断言失败:?MyFunction:需要非空参数

预期:ptr != nullptr

来源:C:\MyProject\src.cpp,第 22 行

Nice and clean, feel free to use it in your code =)

漂亮干净,随意在你的代码中使用它 =)

回答by Zero

BOOST_ASSERT_MSG(expre, msg)

http://www.boost.org/doc/libs/1_51_0/libs/utility/assert.html

http://www.boost.org/doc/libs/1_51_0/libs/utility/assert.html

You could either use that directly or copy Boost's code. Also note Boost assert is header only, so you could just grab that single file if you didn't want to install all of Boost.

您可以直接使用它或复制 Boost 的代码。另请注意,Boost 断言仅是标题,因此如果您不想安装所有 Boost,则可以只获取该单个文件。

回答by metamorphosis

As zneak's answer convolutes the code somewhat, a better approach is to merely comment the string text you're talking about. ie.:

由于 zneak 的回答使代码有些复杂,因此更好的方法是仅评论您正在谈论的字符串文本。IE。:

assert(a == b); // A must be equal to B

Since the reader of the assert error will look up the file and line anyway from the error message, they will see the full explanation here.

由于断言错误的读者无论如何都会从错误消息中查找文件和行,他们将在此处看到完整的解释。

Because, at the end of the day, this:

因为,在一天结束时,这:

assert(number_of_frames != 0); // Has frames to update

reads better than this:

比这更好读:

assert(number_of_frames != 0 && "Has frames to update");

in terms of human parsing of code ie. readability. Also not a language hack.

在人工解析代码方面,即。可读性。也不是语言黑客。

回答by Merlyn Morgan-Graham

assert is a macro/function combination. you can define your own macro/function, using __FILE__, __BASE_FILE__, __LINE__etc, with your own function that takes a custom message

assert 是一个宏/函数组合。你可以定义自己的宏/功能,使用__FILE____BASE_FILE____LINE__等,用自己的函数,它的自定义消息

回答by Jichao

For vc, add following code in assert.h,

对于vc,在assert.h中添加如下代码,

#define assert2(_Expression, _Msg) (void)( (!!(_Expression)) || (_wassert(_CRT_WIDE(#_Msg), _CRT_WIDE(__FILE__), __LINE__), 0) )