`mpl :: plus <mpl :: int_ <1>, mpl :: int_ <2>> :: type` is not the same type as` mpl :: int_ <3> `?

The code below reproduces behavior that I really don't understand in the MPL library with acceleration:

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

I have a question: why is mpl::plus<one,two>::type not the same type as three ?

I ran into this problem trying to solve the exercises at the end of Chapter 3 of the C ++ Template Meta-Programming . I already tried to look into <boost/mpl/plus.hpp> and turn it on there, but the code was too complicated for me to be clear.

+4
source share
1 answer

The return type plus guaranteed only by an integral constant. You have no guarantee over this exact type, therefore, your statement is allowed to fail.

The exact types are:

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

It is not intuitive. One problem is that plus<int_, int_> could theoretically return integral_c , where the first argument has a large capacity, and then int_ in case of overflow.

For debugging a type printer can be useful:

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

All Articles