先看定義在頭文件中的語句:
template <bool x> struct STATIC_ASSERTION_FAILURE;
template <> struct STATIC_ASSERTION_FAILURE<true> { enum { value = 1 }; };
template<int x> struct static_assert_test{};
…
使用的是顯示轉換
// Note that the argument to the assert is explicitly cast to bool using old-
// style casts: too many compilers currently have problems with static_cast
// when used inside integral constant expressions.
…
#elif defined(BOOST_MSVC)
#define BOOST_STATIC_ASSERT( B ) \
typedef ::boost::static_assert_test<\
sizeof(::boost::STATIC_ASSERTION_FAILURE< (bool)( B ) >)>\ // ***********
BOOST_JOIN(boost_static_assert_typedef_, __COUNTER__)
關鍵的地方在于 sizeof() 中的句子。當 (bool)( B ) 為 false 時,因為沒有這個特化版本,編譯器將報錯,如
《Beyond the C++ Standard Library: An Introduction to Boost》中所述:
Error: use of undefined type
'boost::STATIC_ASSERTION_FAILURE<false>'
BOOST_JOIN(X, Y) 最終解釋為 X##Y。__COUNTER__ 在 MSDN 中的描述:
Expands to an integer starting with 0 and incrementing by 1 every time it is used in a compiland.
每使用一次它就增1。
posted on 2009-12-04 13:05
崇文 閱讀(865)
評論(1) 編輯 收藏 引用