c++11新特性--static_assert

來源:互聯網
上載者:User

static_assert:

這個宏用於檢測和診斷編譯時間錯誤。編譯期,這是一個與 CRT-assert(運行時宏)相反的宏。這個好東西用於檢測編譯時間程式的不變數。

這需要一個運算式可以被計算為 bool 或 string (字串)。如果這個運算式的值為 false ,那麼編譯器會出現一個包含特定字串的錯誤,同時編譯失敗。如果為 true 那麼沒有任何影響。

我們可以在以下使用 static_assert

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(120) : 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(div!=0, "Bad arguments.....leading to division by zero");   }       void main()   {        Divide<int,0> ();       // The above line will generate       // error C2338: Bad arguments.....leading to division by zero   }  
請記住,static_asset 是在編譯時間執行的,不能用於檢測運行時的值,向下面函數的參數。

[cpp]  view plain  copy void Divide(int a, int b)   {        static_assert(b==0, “Bad arguments.....leading to division by zero”);  

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.