Hallo!
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));
When the assertion fails I want the normal output plus for example "x was 100".
Yes, this is possible.
To enable expression like
better_assert((0 < x) && (x < 10), std::string("x was ") + myToString(x));
, we are supposed to have a corresponding macro in a form ofin which
print_assertion
is a proxy function to do the assertion. When theEXPRESSION
is evaluatedfalse
, all the debug information, the__VA_ARGS__
, will be dumped tostd::cerr
. This function takes arbitrary numbers of arguments, thus we should implement a variadic templated function:In the previous implementation, the expression
(out << ... << args) << std::endl;
make use of fold expression in C++17 (https://en.cppreference.com/w/cpp/language/fold); the constant expressiondebug_mode
is related to the compilation options passed, which is can be defined asIt also worth mentioning that the expression
if constexpr( debug_mode )
makes use of constexpr if (https://en.cppreference.com/w/cpp/language/if) imported since C++17.To wrap everything up, we have:
A typical test case demonstrating its usage can be:
This will produce something error message like:
And the full source code is available in this repo: https://github.com/fengwang/better_assert
You are out of luck here. The best way is to define your own
assert
macro.Basically, it can look like this:
This will define the
ASSERT
macro only if the no-debug macroNDEBUG
isn’t defined.Then you’d use it like this:
Which is a bit simpler than your usage since you don’t need to stringify
"x was "
andx
explicitly, this is done implicitly by the macro.For the sake of completeness, I published a drop-in 2 files assert macro implementation in C++:
Will prompt you with:
Where
abort()
(on Windows, the system will prompt the user to attach a debugger)abort()
immediatelyYou can find out more about it there:
Hope that helps.
going along with Konrad Rudolf's answer you can do it a bit more concise with
which also works in C,
it works using the general idea from some of the answers to the question you linked, but the macro allows it to be a little more flexible
A better alternative is to teach the debugger to stop on assert when it fails, then you could examine not only the x value but any other information including call stack. Perhaps, this is what you are really looking for. Sample implementation is mentioned here Ways to show your co-programmers that some methods are not yet implemented in a class when programming in C++