Compile-time assertion?

后端 未结 12 1009
春和景丽
春和景丽 2020-11-27 06:09

Is there a way I can assert that two constant expressions are equal at compile time?

e.g. I want this to cause a compile-time error

enum { foo=263,          


        
12条回答
  •  借酒劲吻你
    2020-11-27 06:36

    For another version of a static assert, that you can glorify by adding a better name, you can use:

    // name must be a valid identifier
    #define STATIC_ASSERT( condition, name )\
        typedef char assert_failed_ ## name [ (condition) ? 1 : -1 ];
    

    And use as:

    STATIC_ASSERT( x == y, constants_must_be_same );
    

    The compiler will trigger an error similar to:

    size of array 'assert_failed_constants_must_be_same' is negative
    

    Which does not seem that helpful, but it will point to the exact line of the assert, and after a while you will start processing that error message as static assert failed

提交回复
热议问题