2008-10-11 97 views

回答

15

[回答我的問題]

這要看情況。這是一個橙子比較的蘋果。雖然相似,但這些宏不可互換。以下是每個工作原理的總結:

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; 
} 

爲了便於比較,這裏是線19和21產生我的編譯器(微軟的Visual C++ 2008)錯誤信息以上:

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不太詳細,但其錯誤消息可能不太清晰(取決於您的編譯器)。

3

BOOST_MPL_ASSERT(仍然)通常被認爲更好。從中看到的消息更容易看到(並理解,如果您使用BOOST_MPL_ASSERT_MSG)。幾個月前有一些談論貶低BOOST_STATIC_ASSERT,雖然我認爲每個人最終都同意世界上仍有空間。