编译期错误检查的问题
通过特化模版达到在编译期检查出类型转换不安全
代码如下
template <bool >
class Compile_time_checker
{
public:Compile_time_checker(...){ };// 一个可以进任何参数的构造函数
};
template<>
class Compile_time_checker<false>//特化该模版
{ // no contructor
};
#define STATIC_CHECK(expr,msg)\
{\
class ERROR_##msg{ };\
sizeof(Compile_time_checker<(expr)>(ERROR_##msg( ) )) ;\
}
template<class To, class From>
To safe_reinterpret_cast(From from)
{ STATIC_CHECK(sizeof(From)<=sizeof(To),
TOO_NARROW);
return reinterpret_cast<To>(from);
}
int main()
{
void* m= new char;
char i= safe_reinterpret_cast<char>(m);
return 0;
}
不知道哪里写错了 请牛人指点下。