c++11新特性--static_assert
来源:互联网 发布:js幻灯片切换 编辑:程序博客网 时间:2024/06/10 17:06
static_assert:
这个宏用于检测和诊断编译时错误。编译期,这是一个与 CRT-assert(运行时宏)相反的宏。这个好东西用于检测编译时程序的不变量。
这需要一个表达式可以被计算为 bool 或 string (字符串)。如果这个表达式的值为 false ,那么编译器会出现一个包含特定字符串的错误,同时编译失败。如果为 true 那么没有任何影响。
我们可以在以下使用 static_assert
A. namespace / global scope
static_assert(sizeof(void*) == 4,"not supported");
B.class scope
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:
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 是在编译时执行的,不能用于检测运行时的值,向下面函数的参数。
void Divide(int a, int b){ static_assert(b==0, “Bad arguments.....leading to division by zero”);// sorry mate! the above check is not possible via static_assert...use some other means}
static_assert 这个声明对于模板的调试非常有用,编译器快速执行这个常量表示式参数(不能依赖模板参数)。否则编译器当模板实例化时执行这个常量表达式的参数。
- c++11新特性--static_assert
- c++11新特性--static_assert
- C++ 0x 新特性(4):Static_assert
- C++11新特性(四)static_assert, share_ptr, unique_ptr简单使用
- C+11 新特性
- c++特性:static_assert
- VS2010 中的 C++ 0x 新特性:Lambdas、auto 和 static_assert
- VS2010 中的 C++ 0x 新特性:Lambdas、auto 和 static_assert
- [C++]C++11新特性
- 【C++】 C++11新特性
- c++11 static_assert
- static_assert
- c/c++ 静态断言 static_assert
- 【C++】了解C++11新特性
- C++:C++11新特性详解(1)
- 12c新特性
- Objective-C新特性
- Objective-C新特性
- 修复DISCUZ!的pre_connect_feedlog等表不存在错误
- Photoshop照片模糊变清晰大全
- js+ajax+ext变量作用域问题
- erlang学习网站链接
- 常用DOS命令大全
- c++11新特性--static_assert
- 安排一个简单的软件开发项目的进度
- java package 简写
- LINUX下SMB案例学习
- RLC协议-TM
- Linux经典面试题及答案
- c++小例子代码(1)
- DOS网络命令大全
- jdk内存工具使用