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”);