`MPL ::加< mpl :: int_< 1&gt ;, mpl :: int_< 2> > :: type`与`mpl :: int_< 3>`的类型不同?

时间:2012-07-19 12:59:24

标签: c++ boost c++11 template-meta-programming boost-mpl

下面的代码再现了我对boost MPL库真的不了解的行为:

#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>::typethree的类型不同?

我在尝试解决第3章末尾的练习时遇到了这个问题 C++ Template Meta-Programming。我已经试图查看<boost/mpl/plus.hpp>及其中的内容,但代码太复杂了,我无法理解。

1 个答案:

答案 0 :(得分: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
相关问题