http://erdani.com/index.php/books/modern-c-design/errata/
第25页:
template<bool> struct CompileTimeChecker
{
CompileTimeChecker(...);
};
template<> struct CompileTimeChecker<false> {};
#define STATIC_CHECK(expr, msg) \
{ \
CompileTimeError<expr> \
ERROR_##msg; \
(void)ERROR_##msg; }
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);
}
int main(int argc, _TCHAR* argv[])
{
//STATIC_CHECK( true,
// Destination_Type_Too_Narrow );
double d = 1.0;
int* i = safe_reinterpret_cast<int*>( &d );
return 0;
}
问题1>为什么编译器会抱怨
Destination_Type_Too_Narrow
的使用?问题2>为什么我们总是在宏中使用
(void)
强制转换?为了避免看到未使用的变量警告?
问题3>为什么STATIC_CHECK(false,XXX)将导致编译错误?
谢谢
最佳答案
1:您不是要使用模板函数,因此编译器不会编译任何模板实现,因此assert不会失效。基本上,编译器不会为您不使用的模板发出任何代码(并且此功能在整个模板库(例如boost
)中都用于不同目的)。
2:强制转换为void
是避免未使用变量警告的常用方法。如果断言在您的示例中没有失败,则您的代码中将有一个未使用的变量,并提出警告,表明您可以避免这种情况,这被认为是不好的提示。
关于c++ - 了解编译时断言,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28751998/