Compile-time assertion?

后端 未结 12 1001
春和景丽
春和景丽 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:16

    I would go for one of the available static_asserts.

    • boost::static_assert
    • C++0x static_assert

    But just because I have never tried before I wrote this:

    enum { foo=263, bar=264 };
    
    template
    struct CompileAssert
    {
        bool assert() {}
    };
    
    template<>
    struct CompileAssert  {}; // fail on false.
    
    int main()
    {
        CompileAssert().assert();  // Now I have seen Chad above I like his static 
        CompileAssert().assert();  // method better than using a normal method.
    }                                          // But I tried zero length arrays first did 
                                               // not seem to work
    

提交回复
热议问题