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