一种更好的,能直接给出断言意图的编译时assert的实现像这样.它的好处在于能够定制出错信息.
#include <assert.h>
#include <stdio.h>
//定制出错信息
//这种编译时assert的原理是:利用模板偏特化的特性使得只有bool模板为true时才能编译通过.
template <bool> struct CompileTimeChecker
{
CompileTimeChecker(...);//表示缺省特性是在其构造函数中可接任意型别作为参数
};
template <> struct CompileTimeChecker<false>{ };//覆盖缺省特性,从而不能在构造函数中像缺省特性那样可接受任意型别作为参数
#define STATIC_CHECK(expr,msg)\
{\
class ERROR_##msg{};\
(void)sizeof(CompileTimeChecker<(expr)>(ERROR_##msg()));\
}
template <class To,class From>
To safe_static_cast(From from)
{
STATIC_CHECK(sizeof(From) <= sizeof(To),Destination_Type_Too_Narrorow);
return static_cast<To>(from);
}
int main()
{
int i=0;
double j =0.0;
double p1 = safe_static_cast<double,int>(i);//直接指定From和To的型别
double p2 = safe_static_cast<double>(i);//编译器可根据i的型别,推导From的型别,更灵活
int p3 =safe_static_cast<int>(j);//出错
printf("OK\n");
return 0;
}