您的位置:首页 > 编程语言 > C语言/C++

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

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++