代码之家  ›  专栏  ›  技术社区  ›  jwfearn

哪个是更好的增强断言或增强静态断言?

  •  12
  • jwfearn  · 技术社区  · 17 年前

    我回忆起 BOOST_MPL_ASSERT 曾经是首选。这是真的吗?有人知道为什么吗?

    2 回复  |  直到 17 年前
        1
  •  15
  •   jwfearn    17 年前

    [回答我自己的问题]

    这要看情况而定。这是苹果和橙子的比较。尽管类似,但这些宏不能互换。以下是每种工作方式的摘要:

    BOOST_STATIC_ASSERT( P ) 如果 P != true .

    BOOST_MPL_ASSERT(( P )) 如果 P::type::value != true .

    后一种形式,尽管 需要双括号 ,尤其有用,因为它可以生成更多信息性错误消息 如果 一使用 布尔零元函数 来自boost.mpl或tr1 <type_traits> 作为谓语。

    下面是一个示例程序,演示如何使用(和误用)这些宏:

    #include <boost/static_assert.hpp>
    #include <boost/mpl/assert.hpp>
    #include <type_traits>
    using namespace ::boost::mpl;
    using namespace ::std::tr1;
    
    struct A {};
    struct Z {};
    
    int main() {
            // boolean predicates
        BOOST_STATIC_ASSERT( true );          // OK
        BOOST_STATIC_ASSERT( false );         // assert
    //  BOOST_MPL_ASSERT( false );            // syntax error!
    //  BOOST_MPL_ASSERT(( false ));          // syntax error!
        BOOST_MPL_ASSERT(( bool_< true > ));  // OK
        BOOST_MPL_ASSERT(( bool_< false > )); // assert
    
            // metafunction predicates
        BOOST_STATIC_ASSERT(( is_same< A, A >::type::value ));// OK
        BOOST_STATIC_ASSERT(( is_same< A, Z >::type::value ));// assert, line 19
        BOOST_MPL_ASSERT(( is_same< A, A > ));                // OK
        BOOST_MPL_ASSERT(( is_same< A, Z > ));                // assert, line 21
        return 0;
    }
    

    为了比较,以下是我的编译器(微软Visual C++ 2008)为上面的第19行和第21行生成的错误消息:

    1>static_assert.cpp(19) : error C2027: use of undefined type 'boost::STATIC_ASSERTION_FAILURE<x>'
    1>        with
    1>        [
    1>            x=false
    1>        ]
    1>static_assert.cpp(21) : error C2664: 'boost::mpl::assertion_failed' : cannot convert parameter 1 from 'boost::mpl::failed ************std::tr1::is_same<_Ty1,_Ty2>::* ***********' to 'boost::mpl::assert<false>::type'
    1>        with
    1>        [
    1>            _Ty1=A,
    1>            _Ty2=Z
    1>        ]
    1>        No constructor could take the source type, or constructor overload resolution was ambiguous
    

    所以如果你使用元函数 here )然后作为谓词 BOOST_MPL_ASSERT 对代码来说不那么冗长,断言时信息更丰富。

    对于简单的布尔谓词, BOOST_STATIC_ASSERT 虽然错误消息可能不太清楚(取决于编译器),但对代码的详细程度较低。

        2
  •  3
  •   Head Geek    17 年前

    BOOST_MPL_ASSERT 一般认为更好。从中得到的信息比较容易看到(如果使用 BOOST_MPL_ASSERT_MSG )几个月前有人说要贬低 BOOST_STATIC_ASSERT 尽管我认为每个人最终都同意,世界上仍有发展空间。