2.1 編譯期斷言
有時(shí)候,我們的斷言其實(shí)在編譯時(shí)就可以判斷真假,于是有編譯時(shí)斷言。例如如此實(shí)現(xiàn):
1 #define STATIC_CHECK(expr) {char unnamed[(expr)?1:0];}
如果條件為假,編譯器因大小為0的數(shù)組非法而報(bào)錯(cuò)。但出錯(cuò)信息顯然沒(méi)有實(shí)際意義,可以改進(jìn),使用模板:
1 template<bool> struct CompileTimeError;
2 template<> strcut CompileTimeError<true>{};
3 #define STATIC_CHECK(expr) (CompileTimeError<(expr)!=0>())
如果你試著具現(xiàn)化CompileTimeError<false>,編譯器會(huì)提示“Undefined specialization CompileTimeError<false>”。
(進(jìn)一步改進(jìn)從略)