How to implement a standard-compliant assert macro with an optional formatted message?

后端 未结 3 1462
北海茫月
北海茫月 2021-01-22 01:55

What\'s the way to implement a standard-compliant assert macro with an optional formatted message?

What I have works in clang, but (correctly) triggers the -Wgnu-z

3条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-22 02:25

    The basic solution is to use << on cerr:

    #define MyAssert(expression, msg)                                  \
    do {                                                               \
        if(!(expression))                                              \
        {                                                              \
            std::cerr << msg;                                          \
            abort();                                                   \
        }                                                              \
    } while(0)
    

    This solution uses C++ streams, so you can format the output as you see fit. Actually this is a simplification of a C++17 solution that I'm using to avoid temporaries (people tend to use + instead of << with this solution, triggering some efficiency warnings).

    Use it then like this:

    MyAssert(true, "message " << variable << " units");
    

    I think the optionality is bogus here, as you are outputting "Assertion error:" meaning that you expect a message.

提交回复
热议问题