随笔-14  评论-8  文章-0  trackbacks-0
先看定义在头文件中的语句:
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 崇文 阅读(819) 评论(1)  编辑 收藏 引用

评论:
# re: Boost 中的 BOOST_STATIC_ASSERT 2016-04-22 15:59 | 崇文
2016年4月22日:在没有看下面的内容时,我居然能看懂template <>是第一条语句的特化版,有些东西真的像游泳骑车,难丢难忘,泪流满面!  回复  更多评论
  

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理