2012-07-19 54 views
4

下面的代碼再現行爲我實在不明白升壓MPL庫:`mpl :: plus <mpl :: int_ <1>,mpl :: int_ <2>> :: type`與`mpl :: int_ <3>`不是相同的類型嗎?

#include <boost/type_traits/is_same.hpp> 
#include <boost/mpl/int.hpp> 
#include <boost/mpl/plus.hpp> 

using namespace boost; 

int main() { 
    typedef mpl::int_<1> one; 
    typedef mpl::int_<2> two; 
    typedef mpl::int_<3> three; 
    // The following line breaks compilation... 
    // static_assert(is_same< mpl::plus<one,two>::type, three >::type::value, "Not the same type"); 
    // ...while this works 
    static_assert(mpl::plus<one,two>::type::value == three::value , "Not the same value"); 
    return 0; 
} 

我的問題是:爲什麼mpl::plus<one,two>::type是不一樣的類型three

我在嘗試解決 C++ Template Meta-Programming第3章末尾的練習時遇到了這個問題。我已經試過偷看<boost/mpl/plus.hpp>及其中的內容,但代碼太複雜了,我無法理解。

回答

5

返回類型plus只能保證是一個積分常數。你不能保證它的確切類型,因此你的斷言允許失敗。

的確切類型是這樣的:

mpl::plus<one,two>::type == mpl_::integral_c<int, 3> 
three == foo<mpl_::int_<3> > 

這是不直觀。一個問題是plus<int_, int_>理論上可以返回一個integral_c其中第一個參數具有較大的容量,然後int_在溢出的情況下。

用於調試的type printer可能是有用的:

template<typename> print; // undefined instantiation leads to error with name 
print<three> x; // nice error message 
+0

感謝'模板結構打印;'小費! – Massimiliano 2012-07-19 13:33:34

+0

@Massimiliano還有'mpl :: print',但是至少在'gcc'上看起來很糟糕。不會中止編譯的東西會更好。 – pmr 2012-07-19 13:44:24

+0

作爲旁註,這個註冊爲boost Trac中的一個問題。所以我們知道這是一個問題:) – 2012-07-19 14:38:51