assert - chunhualiao/public-docs GitHub Wiki
You're right that the standard C++ assert()
macro doesn't allow for custom error messages. Here are some good solutions to this limitation:
- Use a custom assert macro that includes a message:
#define ASSERT_MSG(condition, message) do { \
if (!(condition)) { \
std::cerr << "Assertion failed: " << #condition << ", " << message << std::endl; \
std::abort(); \
} \
} while (0)
- Use C++20's
<source_location>
to create more informative errors:
#include <source_location>
void customAssert(bool condition, const char* message,
const std::source_location& location = std::source_location::current()) {
if (!condition) {
std::cerr << "Assertion failed at " << location.file_name() << ":"
<< location.line() << " in " << location.function_name()
<< ": " << message << std::endl;
std::abort();
}
}
- Use a third-party library like Boost.Assert, which provides
BOOST_ASSERT_MSG(expr, msg.c_str())
.
- Use exceptions with descriptive messages for recoverable errors:
if (!condition) {
throw std::runtime_error("Failed because specific reason XYZ");
}
- Use static_assert() for compile-time checks - this does support custom messages:
static_assert(sizeof(int) >= 4, "This program requires integers of at least 32 bits");
- Create a logging-based assertion system that integrates with your logging infrastructure.
Which approach would work best depends on your specific needs and code structure.