BOOST_STATIC_ASSERT without boost

前端 未结 6 1209

Since boost is forbidden in a company I work for I need to implement its functionality in pure C++. I\'ve looked into boost sources but they seem to be too complex to unders

6条回答
  •  天涯浪人
    2020-11-30 02:59

    One other trick (which can be used in C) is to try to build an array with a negative size if the assert fail:

    #define ASSERT(cond) int foo[(cond) ? 1 : -1]
    

    as a bonus, you may use a typedef instead of an object, so that it is usable in more contexts and doesn't takes place when it succeed:

    #define ASSERT(cond) typedef int foo[(cond) ? 1 : -1]
    

    finally, build a name with less chance of name clash (and reusable at least in different lines):

    #define CAT_(a, b) a ## b
    #define CAT(a, b) CAT_(a, b)
    #define ASSERT(cond) typedef int CAT(AsSeRt, __LINE__)[(cond) ? 1 : -1]
    

提交回复
热议问题