以前看過很長時間的boost,記得上面有STATIC_ASSERT
在loki庫中也有類似的宏
1 LOKI_STATIC_CHECK(expr, msg)
其中expr代表要斷言的表達(dá)式
當(dāng)其為假,則讓程序無法通過編譯
其實(shí)現(xiàn)很簡單
利用模板特化:
1 template<int> struct CompileTimeError;
2 template<> struct CompileTimeError<true> {};
當(dāng)表達(dá)式為真則使用模板特化形式
注意其模板在這里僅僅做前向引用
再看具體的宏:
1 #define LOKI_STATIC_CHECK(expr, msg) \
2 { Loki::CompileTimeError<((expr) != 0)> ERROR_##msg; (void)ERROR_##msg; }
使用代碼塊(statement block)
聲明一個編譯時錯誤對象
(具體原因在于當(dāng)條件為假則模板對象沒有具體實(shí)現(xiàn),拋出一個未定義完全的對象)
9 D:\Dev-Cpp\prj\test\main.cpp aggregate `Loki::CompileTimeError<0> ERROR_wo' has incomplete type and cannot be defined
對于其宏的實(shí)現(xiàn)在我看來
(void)ERROR_##msg;這句是多余的(不知道這句的作用是什么??誰能告訴我)