C++11 New Characteristics--static_assert

Source: Internet
Author: User

Static_assert:

This macro is used to detect and diagnose compile-time errors. Compile-time, which is a macro that is the opposite of Crt-assert (run-time macro). This good thing is used to detect the invariants of a compile-time program.

This requires an expression that can be evaluated as either bool or string (string). If the value of this expression is false, then the compiler will appear with an error containing a specific string, and the compilation fails. If True Then there is no effect.

we can use Static_assert in the following

A. Namespace/global scope

[CPP] view plain copy static_assert (sizeof (void*) = = 4, "not supported");

B.class Scope

[CPP]  View plain  copy template<class t, int _n>      class  myvec   {        static_assert ( _n > 0 ,   "How the hell the size of a vector be negative");   };      void main ()    {       myvec<int,  -2> Vec_;       // The above line will  throw error as shown below  ( in vs2010 compiler):        //   > \main_2.cpp ( : error C2338: How ) the hell the size of a vector be negative        //   > main_2.cpp (126)  : see reference to class  template instantiation  ' myvec<t,_n /> '        //      being compiled       //   > with       //   > [        //         > T=int,        //        > _n=-2       //    > ]          // This is fine            MyVec<int, 100> Vec_;  }  

C. Block scope:

[CPP] view plain copy template<typename T, int div> void Divide () {Static_assert (d   Iv!=0, "Bad arguments.....leading to division by Zero");       } void Main () {divide<int,0> (); The above line would generate//error C2338:bad arguments.....leading to division by zero}
Keep in mind that Static_asset is executed at compile time and cannot be used to detect run-time values, to the parameters of the following function.

[CPP]   View plain  copy void divide (int a, int  b)    {        static_assert (b==0,  "bad arguments ...) Leading to division by zero ");  

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.