`mpl :: plus <mpl :: int_ <1>,mpl :: int_ <2 >>> :: type`与`mpl :: int_ <3>`的类型不同?

Mas*_*ano 4 c++ boost boost-mpl template-meta-programming c++11

下面的代码再现了我对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;
}
Run Code Online (Sandbox Code Playgroud)

我的问题是:为什么mpl::plus<one,two>::type不是同一类型three

我在尝试解决C++ Template Meta-Programming第3章末尾的练习时遇到了这个问题 .我已经试图偷看它<boost/mpl/plus.hpp>和其中的包含,但代码太复杂,我不能理解.

pmr*_*pmr 5

返回类型plus仅保证是一个整数常量.你有过它的确切类型无法保证,因此您的断言是允许失败.

确切的类型是这样的:

mpl::plus<one,two>::type == mpl_::integral_c<int, 3>
three == foo<mpl_::int_<3> >
Run Code Online (Sandbox Code Playgroud)

这是不直观的.一个问题是plus<int_, int_>理论上可以返回integral_c第一个参数具有更大容量的位置,然后int_在溢出的情况下.

对于调试,type printer可能很有用:

template<typename> print; // undefined instantiation leads to error with name
print<three> x; // nice error message
Run Code Online (Sandbox Code Playgroud)