c++特性:static_assert
2016-02-01 15:18
537 查看
主要参考:c++11新特性–static_assert
static_assert:
这个宏用于检测和诊断编译时错误。编译期,这是一个与 CRT-assert(运行时宏)相反的宏。这个好东西用于检测编译时程序的不变量。
这需要一个表达式可以被计算为 bool 或 string (字符串)。如果这个表达式的值为 false ,那么编译器会出现一个包含特定字符串的错误,同时编译失败。如果为 true 那么没有任何影响。
我们可以在以下使用 static_assert
A. namespace / global scope
B.class scope
C. block scope:
请记住,static_asset 是在编译时执行的,不能用于检测运行时的值,向下面函数的参数
static_assert 这个声明对于模板的调试非常有用,编译器快速执行这个常量表示式参数(不能依赖模板参数)。否则编译器当模板实例化时执行这个常量表达式的参数。
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++实现JNI接口需要注意的事项
- 关于指针的一些事情
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- Lua中调用C++函数示例
- Lua教程(一):在C++中嵌入Lua脚本
- Lua教程(二):C++和Lua相互传递数据示例
- C++联合体转换成C#结构的实现方法
- C++高级程序员成长之路
- C++编写简单的打靶游戏
- C++ 自定义控件的移植问题
- C++变位词问题分析
- C/C++数据对齐详细解析
- C++基于栈实现铁轨问题
- C++中引用的使用总结
- 使用Lua来扩展C++程序的方法
- C++中调用Lua函数实例
- Lua和C++的通信流程代码实例
- C与C++之间相互调用实例方法讲解
- 解析C++中派生的概念以及派生类成员的访问属性