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:

  1. 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)
  1. 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();
    }
}
  1. Use a third-party library like Boost.Assert, which provides BOOST_ASSERT_MSG(expr, msg.c_str()).

BOOST_ASSERT_MSG

  1. Use exceptions with descriptive messages for recoverable errors:
if (!condition) {
    throw std::runtime_error("Failed because specific reason XYZ");
}
  1. 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");
  1. 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.