What does static_assert do, and what would you use it for?

前端 未结 8 734
生来不讨喜
生来不讨喜 2020-12-04 06:21

Could you give an example where static_assert(...) (\'C++11\') would solve the problem in hand elegantly?

I am familiar with run-time assert(...)<

8条回答
  •  心在旅途
    2020-12-04 07:01

    Off the top of my head...

    #include "SomeLibrary.h"
    
    static_assert(SomeLibrary::Version > 2, 
             "Old versions of SomeLibrary are missing the foo functionality.  Cannot proceed!");
    
    class UsingSomeLibrary {
       // ...
    };
    

    Assuming that SomeLibrary::Version is declared as a static const, rather than being #defined (as one would expect in a C++ library).

    Contrast with having to actually compile SomeLibrary and your code, link everything, and run the executable only then to find out that you spent 30 minutes compiling an incompatible version of SomeLibrary.

    @Arak, in response to your comment: yes, you can have static_assert just sitting out wherever, from the look of it:

    class Foo
    {
        public: 
            static const int bar = 3;
    };
    
    static_assert(Foo::bar > 4, "Foo::bar is too small :(");
    
    int main()
    { 
        return Foo::bar;
    }
    
    $ g++ --std=c++0x a.cpp
    a.cpp:7: error: static assertion failed: "Foo::bar is too small :("
    

提交回复
热议问题