Add custom messages in assert?

后端 未结 8 1004
心在旅途
心在旅途 2020-12-04 07:18

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

相关标签:
8条回答
  • 2020-12-04 07:42

    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

    0 讨论(0)
  • 2020-12-04 07:45

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

    #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

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

    0 讨论(0)
提交回复
热议问题