对编译期assertion,我的理解是:让编译器在编译期进行更多的检查,而不仅限于对类型之类的检查,以此将错误在编译期而不是运行前暴露出来。对于模板来说,这样尤为重要,因为如果使用模板出错,那么debug是相当的麻烦。
对于编译期assertion,最重要的是,如何让编译期的错误信息更有价值,即是,要花相当精力在编译期错误信息的定制上。
以下是来自于《C++设计新思维》中的例子。
/*
#define STATIC_CHECK( expr ) { char unnamed[ (expr)? 1 : 0 ]; }
template < class To, class From >
To safe_rein_cast( From from )
{
STATIC_CHECK( sizeof(From) < sizeof(To) );
return reinterpret_cast<To> (from);
}
*/
/*
template < bool > struct CompileTimeError;
template < > struct CompileTimeError< true > { };
#define STATIC_CHECK( expr ) /
( CompileTimeError < ( (expr) != 0) > ( ) )
template < class To, class From >
To safe_rein_cast( From from )
{
STATIC_CHECK( sizeof(From) < sizeof(To) );
return reinterpret_cast<To> (from);
}
*/
/*
template < bool >
struct CompileTimeChecker
{
CompileTimeChecker ( ... );
};
template<> struct CompileTimeChecker< false > { };
#define STATIC_CHECK( expr, msg ) /
{/
class ERROR_##msg { }; /
(void) sizeof( CompileTimeChecker< (expr) > ( ERROR_##msg::ERROR_##msg( ) ) ); /
}
template < class To, class From >
To safe_rein_cast( From from )
{
STATIC_CHECK( (sizeof(From) <= sizeof(To)), Destination_Type_Too_Narrow );
return reinterpret_cast<To> (from);
}
*/
个人认为,这样定制的信息业并不能达到很好的效果,也容易让人看得云里雾里……也许编写一个错误信息后台处理程序更有价值?