2.1编译期(Compile-Time)Assertions(断言) (P.23)
前言--古老的执行期断言:
template <class To, class From>
To safe_reinterpret_cast(From from)
{
assert(sizeof(From) <= sizeof(To) ); //问题一:assert()发生在执行期
return reinterpret_cast<To>(from); //问题二:reinterpret_cast不可移植
}
一、编译期断言--另类assert();_1(P.24)
#define STATIC_CHECK(erpr) {char unnamed [(erpr) ? 1:0];}
它依赖一个事实:大小为0的array是非法的。
那么现在:
template <class To, class From>
To safe_reinterpret_cast(From from)
{
STATIC_CHECK(sizeof(From) <=sizeof(To));
return reinterpret_cast<To>(from);
}
...
void* somePointer=...;
char c = safe_reinterpret_cast<char>(somePointer);
//如果在你的系统中,指针大于字符的话,编译器就会抱怨:“你正试图产生一个长度为0的array”。
问题:收到的错误消息无法正确表达错误信息。
二、编译期断言--另类assert();_2(P.25)
template<bool> struct CompileTimeError;
template<> struct CompileTimeError<true> {};
#define STATIC_CHECK(expr) /
( CompileTimeError<expr> !=0>() )
编译期断言assert();_2++: //改良版:
template<bool> struct CompileTimeChecker
{
CompileTimeChecker(...) ;//这是C/C++支持的非定量任意参数表
};
template<> struct CompileTimeChecker<ture> {}; //特化体
#define STATIC_CHECK(expr,msg) /
{/
class ERROR_##msg {}; / //##是个罕被使用的C++操作符
(void)sizeof(CompileTimeChecker<expr> (ERROR_##msg()) ); /
}
三、assert();_2++: //测试:
template<class To, class From>
To safe_reinterpret_cast(From from)
{
STATIC_CHECK(sizeof(From) <=sizeof(To),
Destination_Type_Too_Narrow);
return reinterpret_cast<To> (from);
}
...
void* somePointer = ...;
char c = safe_reinterpret_cast<char> (somePointer);
====(P.26)宏被处理完毕后,上述函数模板safe_reinterpret_cast会被展开为如下模板函数:
template <calss To, class From>
To safe_reinterpret_cast(From from)
{
{
class ERROR_Destination_Type_Too_Narrow {}; //定义了一个空的local class
(void)sizeof(
CompileTimeChecker<(sizeof(From) <= sizeof(To) )>( //暂时对象
ERROR_Destination_Type_Too_Narrow()) );
}
return reinterpret_cast<To> (from);
}
编译器输出:"Error:Cantnot convert ERROR_Destunation_Type_Too_Narrow to CompileTimeChecker<false>",真是太棒了,本小节结束。
2.2 Partial Template Specialization(模板偏特化) (P.26)
并不存在Template函数的偏特化
2.3 局部类 (Local Classes)
2.4 常数映射为类别 (Mapping Integral Constans to Types) (P.29)
2.5 型别对型别的影射 (Type-to-Type Mapping)
2.6 类别选择 (Type Seletion)