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 这个声明对于模板的调试非常有用,编译器快速执行这个常量表示式参数(不能依赖模板参数)。否则编译器当模板实例化时执行这个常量表达式的参数。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值