c++11新特性--static_assert

static_assert:

这个宏用于检测和诊断编译时错误。编译期,这是一个与 CRT-assert(运行时宏)相反的宏。这个好东西用于检测编译时程序的不变量。

这需要一个表达式可以被计算为 bool 或 string (字符串)。如果这个表达式的值为 false ,那么编译器会出现一个包含特定字符串的错误,同时编译失败。如果为 true 那么没有任何影响。

我们可以在以下使用 static_assert

A. namespace / global scope

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

B.class scope

[cpp]  view plain  copy
  1. template<class T, int _n>  
  2.   
  3. class MyVec  
  4. {   
  5.     static_assert( _n > 0 , "How the hell the size of a vector be negative");  
  6. };  
  7.   
  8. void main()  
  9. {  
  10.     MyVec<int, -2> Vec_;  
  11.     // The above line will throw error as shown below ( in VS2010 compiler):  
  12.     //   > \main_2.cpp(120) : error C2338: How the hell the size of a vector be negative  
  13.     //   > main_2.cpp(126) : see reference to class template instantiation 'MyVec<t,_n />'  
  14.     //     being compiled  
  15.     //   > with  
  16.     //   > [   
  17.     //        > T=int,   
  18.     //       > _n=-2  
  19.     //   > ]  
  20.   
  21.     // This is fine  
  22.         MyVec<int, 100> Vec_;  
  23. }  

C. block scope:

[cpp]  view plain  copy
  1. template<typename T, int div>  
  2. void Divide( )  
  3. {   
  4.     static_assert(div!=0, "Bad arguments.....leading to division by zero");  
  5. }   
  6.   
  7. void main()  
  8. {   
  9.     Divide<int,0> ();  
  10.     // The above line will generate  
  11.     // error C2338: Bad arguments.....leading to division by zero  
  12. }  

请记住,static_asset 是在编译时执行的,不能用于检测运行时的值,向下面函数的参数。

[cpp]  view plain  copy
  1. void Divide(int a, int b)  
  2. {   
  3.     static_assert(b==0, “Bad arguments.....leading to division by zero”);  
  4.     // sorry mate! the above check is not possible via static_assert...use some other means  
  5. }  

static_assert 这个声明对于模板的调试非常有用,编译器快速执行这个常量表示式参数(不能依赖模板参数)。否则编译器当模板实例化时执行这个常量表达式的参数。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值